开发者

Bypass Data Annotations validation on ASP.NET MVC 2

开发者 https://www.devze.com 2023-01-10 17:29 出处:网络
I would like to know if it\'s possible to bypass the validation of one property which is using Data Annotations. Since I use the model across multiple pa开发者_运维知识库ges, there\'s a check I need i

I would like to know if it's possible to bypass the validation of one property which is using Data Annotations. Since I use the model across multiple pa开发者_运维知识库ges, there's a check I need in some, but not in others, so I would like it to be ignored.

Thaks!


You could use FluentValidation, which uses as external validator class. In this case you would implement a different validator class for each scenario.

http://fluentvalidation.codeplex.com/

Example:

using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
    public CustomerValidator() {
        RuleFor(customer => customer.Surname).NotEmpty();
        RuleFor(customer => customer.Forename).NotEmpty()
            .WithMessage("Please specify a first name");
    }
}

public class CustomerValidator2: AbstractValidator<Customer> {
    public CustomerValidator() {
        RuleFor(customer => customer.Surname).NotEmpty();
    }
}

Customer customer = new Customer();

CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

CustomerValidator2 validator2 = new CustomerValidator2();
ValidationResult results2 = validator2.Validate(customer);

results would have 2 validation errors
results2 would have 1 validation error for the same customer


I don't believe this is possible with Data Annotations. I know the Microsoft Enterprise Library Validation Application Block has the notion of rule sets to group validations. This allows you to validate an object on several rule sets, for instance the default ruleset and on some pages the extended rule set. Data Annotations does not have something like rule sets.

Here is an example using VAB:

public class Subscriber
{
    [NotNullValidator]
    [StringLengthValidator(1,200)]
    public string Name { get; set; }

    [NotNullValidator(Ruleset="Persistence")]
    [EmailAddressValidator]
    public string EmailAddress { get; set; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消