代码之家  ›  专栏  ›  技术社区  ›  dariol

不同场景下的实体验证

  •  0
  • dariol  · 技术社区  · 17 年前

    假设我有两个字段的实体。某些字段在某些特定状态下是必需的,但其他字段仅在进一步/其他状态下需要。

    public class Entity
    {
        //Required always
        public SomeReference {}
    
        //Required in specific situation/scenario
        public OtherReference {}
    }
    

    寻求帮助: 乌迪大汉对此有一些想法。 http://www.udidahan.com/2007/04/30/generic-validation/

    2 回复  |  直到 17 年前
        1
  •  1
  •   Dai Bok    16 年前

    我有一个解决方案,我正在使用。我使用 Fluent validation

    public class User {
        public virtual string Name { get; set; }
        public virtual string Email { get; set; }
        public virtual string Password { get; set; }
        public virtual Address Address { get; set; }        
    }
    
    public class Address {
        public virtual string Address1 { get; set; }
        public virtual string PostCode { get; set; }
    }
    

        public AddressValidator() {
            RuleFor(address => address.Address1)
                .NotNull()
                .WithMessage("Please enter the first line of your address");
    
            RuleFor(address => address.PostCode)
                .NotNull()
                .WithMessage("Please enter your postcode")
                .Matches(UK_POSTCODE_REGEX)
                .WithMessage("Please enter a valid post code!");
        }
    
        public UserValidator() {
            RuleFor(user => user.FirstName)
                .NotNull()
                .WithMessage("Please provide a first name")
                .Length(3, 50)
                .WithMessage("First name too short");
    
            RuleFor(user=> user.Password)
                .Length(8, 50)
                .WithMessage("Password is too short");
        }
    

    然后创建一个模型验证器,例如,假设我们有一个表单,用户在其中输入一个地址,我们创建一个AddressModelValidator,可以重用我们编写的验证器:

        public AddressModelValidator()  {
            RuleFor(user => user.id)
                .NotNull()
                .WithMessage("An error has occured, please go back and try again");
    
            RuleFor(user => user.Address).SetValidator(new AddressValidator());
        }
    

    所以,考虑一下,你真的可以创建一些好的模型,并减少你的验证代码重复!

        2
  •  0
  •   Andrew Siemer    17 年前

    public void Validate()
    {
        if(!IsValid)
            throw new ValidationException("Rule violations prevent saving");
    }
    
    public bool IsValid
    {
        get { return GetRuleViolations().Count() == 0;}
    }
    
    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if(this.TermID == 0)
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(1), "agreeWithTerms");
    
        if(ValidationService.ValidateDate(this.Birthdate.ToString()))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(2), "birthDate");
    
        if (!(Username.Length >= ConfigurationService.GetMinimumUsernameLength()) ||
            !(Username.Length <= ConfigurationService.GetMaximumUsernameLength()))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(5), "username");
    
        if(ValidationService.ValidateUsernameComplexity(Username))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(6), "username");
    
        if (AccountID == 0 && ObjectFactory.GetInstance<IAccountRepository>().UsernameExists(this.Username))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(7), "username");
    
        if (!ValidationService.ValidateEmail(Email))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(8), "email");
    
        if (AccountID == 0 && ObjectFactory.GetInstance<IAccountRepository>().EmailExists(this.Email))
            yield return new RuleViolation(HelpMessageService.GetHelpMessageBodyByID(9), "email");
    
        yield break;
    }
    

    请阅读此处,以充分了解这一点: http://nerddinnerbook.s3.amazonaws.com/Part3.htm

    推荐文章