Conditional Validation in ASP.NET MVC 3

I’m currently working on a project that has various forms where some fields are only required if another field has a certain value or is blank.

For example, it is a common requirement that a user must enter a value for either phone OR mobile. You can’t put a Required attribute on either of them as that would not solve the requirement.

Using the library developed by Simon Ince you could define it like this in your model;

[RequiredIf("Mobile", "", ErrorMessage="Please enter a value in either Phone or Mobile")]
 public string Phone { get; set; }

[RequiredIf("Phone", "", ErrorMessage = "Please enter a value in either Mobile or Phone")]
 public string Mobile { get; set; }

Here are some relevant links to add custom validation logic, both client and server side, to your MVC projects:

http://blogs.msdn.com/b/simonince/archive/2011/09/29/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3.aspx

http://blogs.msdn.com/b/stuartleeks/archive/2010/08/06/asp-net-mvc-adding-client-side-validation-to-propertiesmustmatchattribute.aspx

http://foolproof.codeplex.com/

Tagged with: , ,
Posted in Uncategorized

Leave a comment