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:

Tagged with: , ,
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: