首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不同场景下的实体验证

不同场景下的实体验证
EN

Stack Overflow用户
提问于 2009-06-22 20:13:24
回答 2查看 401关注 0票数 0

假设我有几个字段的实体。某些字段在某些特定状态下是必需的,但其他字段仅在更远/其他状态下是必需的。

代码语言:javascript
复制
public class Entity
{
    //Required always
    public SomeReference {}

    //Required in specific situation/scenario
    public OtherReference {}
}

如何使用一些已知的验证框架来实现该场景,或者如何自己实现?

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

EN

回答 2

Stack Overflow用户

发布于 2009-12-21 18:24:07

我有一个目前正在使用的解决方案。我使用Fluent validation,并且还在习惯它。我可以给你举一个我有一个简单场景的例子。也许这会有帮助。我有一个user类,有一个address对象属性。有时,我只想验证用户详细信息(姓名、电子邮件、密码等),而在另一种情况下,我想验证用户地址(第一行、邮政编码等)。

类如下所示:

代码语言:javascript
复制
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; }
}

然后我有两个(简化的)验证器,一个用于地址,另一个用于用户:

代码语言:javascript
复制
    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,并且可以重用我们编写的验证器:

代码语言:javascript
复制
    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());
    }

所以,只要想一想,你就可以创建一些很好的模型,并减少验证代码的重复!

票数 1
EN

Stack Overflow用户

发布于 2009-06-22 20:19:50

我的首选是将电子邮件和日期验证等常见验证功能本地化到一个ValidationService类中,我可以将我的对象传递到该类中。不过,对于其余部分,我倾向于将验证放在类本身中。如果我使用LINQ to SQL,那么我可以在我的对象上创建一个Validate()方法,在将对象保存到数据库之前,LINQ to SQL将调用该方法,如下所示:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1029173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档