1

I've been directed to an very nice article that shows how to create a Custom Validator from start to finish. My only problem is that this only works on single fields: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

What if I need to validate against 2 or more properties in my Model? How can I pass my entire Model into the Validator?

NOTE: To be clear, I really don't want to have to resort to validating the entire model on post back... that would defeat the purpose of this method.

1 Answer 1

5

You need to use a custom validate attribute and decorate your model with it, not individual properties:

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyCustomValidatorAttribute : ValidationAttribute 
{
    public override bool IsValid(object value) 
    {
        // value here will be the model instance you could cast
        // and validate properties
        return true;
    }
}

and then decorate your model with it:

[MyCustomValidator]
public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

As an alternative to data annotations to perform validation I would more than strongly recommend you FluentValidation.NET. It also has great integration with ASP.NET MVC.

Sign up to request clarification or add additional context in comments.

1 Comment

[AttributeUsage(AttributeTargets.Class)]?

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.