Peter Nguyen Team : Web Development Tags : Web Development

Conditional validation for MVC applications

Peter Nguyen Team : Web Development Tags : Web Development

Data annotations, introduced in MVC2 are a great way to manage validation for your view models.

However, time and time again, you come across the standard multi-step form development question – I need field A to be required only if field B is set. Built in annotations don’t support this out of the box, so I like to use a package called Foolproof Validation.

Foolproof makes conditional validation fairly easy. It has built-in client-side validation support, so the conditional validation will be performed both client and server side.

Take this example:

public bool Married { get; set; }

[RequiredIfTrue("Married")]
public string MaidenName { get; set; }

Setting the Foolproof data annotation ‘RequiredIfTrue’ ensures that MaidenName will be set as required if Married = true.

In addition to this, it includes a suite of required ‘if’ validators:

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

And operator validators:

[Is]
[EqualTo]
[NotEqualTo]
[GreaterThan]
[LessThan]
[GreaterThanOrEqualTo]
[LessThanOrEqualTo]

Check it out: https://foolproof.codeplex.com/