使用Microsoft.Practices.EnterpriseLibrary.Validation.dll验证类成员
public class MyClass { [StringLengthValidator(1, 32, MessageTemplate = "MyValue is too long", Ruleset = "MyRules")] [MyValidator(MessageTemplate="MyValue is invalid", Ruleset = "MyRules")] public string MyValue {get;set;} public ValidationResults Validate() { Validator<MyClass> myValidator = ValidationFactory.CreateValidator<MyClass>("MyRules"); ValidationResults custResults = myValidator.Validate(this); return custResults; } }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class MyValidatorAttribute : ValidatorAttribute { protected override Validator DoCreateValidator(Type targetType) { return new MyValidator(Tag); } } public class MyValidator:Validator<string> { public MyValidator(string tag) : base(string.Empty, tag) { } private bool IsValid(string text) { return false; } protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults) { if (string.IsNullOrEmpty(objectToValidate)) return; if (IsValid(objectToValidate))//cc is found { LogValidationResult(validationResults, GetMessage(objectToValidate,key), currentTarget, key); } } protected override string DefaultMessageTemplate { get { return "Validation failed"; } } }