views:

197

answers:

2

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 pages, there's a check I need in some, but not in others, so I would like it to be ignored.

Thaks!

+1  A: 

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; }
}
Steven
+1  A: 

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
Daniel Dyson