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!

2
  • I asked something similiar to this a while back - short answer is no. stackoverflow.com/questions/2503735/… I ended up having to write up my own validation system to it. You MIGHT be able to write your own model binder to handle it, but I never got around to it. Commented Aug 4, 2010 at 13:52
  • ... that's why they say you should create a separate view model for each view ;) Commented Aug 5, 2010 at 0:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.