Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Conditionally Required Properties

How do you create conditionally required properties with the MVC 3 framework that will work with Client Side Validation as well as Server Side Validation when JS is disabled? For example:

public class PersonModel
{
  [Required] // Requried if Location is not set
  public string Name {get; set;}
  [Range( 1, 5 )] // Requried if Location is not set
  public int Age {get; set;}

  [Required] // Only required if Name and Age are not set.
  public string Location {get; set;}
}

The rules in this example are:

  1. Name and Age are required if Location is not set.
  2. Location is required only if Name and Age are not set.
  3. Doesn't matter if Name, Age and Location are all set.

In the View, I need the result sent to an Action if Name/Age are set. And a different Action if Location is set. I've tried with 2 separate forms with different Get Url's; this works great except the validation rules are causing problems. Preferrably, I would like the use of 2 separate Get action Url's, i.e.,

@model PersonModel

@using( Html.BeginForm( "Age", "Person", FormMethod.Post ) )
{
  @Html.TextBoxFor( x => x.Name )
  @Html.ValidationMessageFor( x => x.Name )
  @Html.TextBoxFor( x => x.Age )
  @Html.ValidationMessageFor( x => x.Age )
  <input type="submit" value="Submit by Age" />
}

@using( Html.BeginForm( "Location", "Person", FormMethod.Post ) )
{
  @Html.TextBoxFor( x => x.Location )
  @Html.ValidationMessageFor( x => x.Location )
  <input type="submit" value="Submit by Location" />
}

Based on the PersonModel above, if the Location is submitted, the validation will fail since the PersonModel is expecting the Name and Age to be set as well. And vice versa with Name/Age.

Given the above mocked up example, how do you create conditionally required properties with the MVC 3 framework that will work with Client Side Validation as well as Server Side Validation when JS is disabled?

like image 287
Metro Smurf Avatar asked Sep 07 '11 13:09

Metro Smurf


1 Answers

You can add custom validation to your model either subclassing ValidationAttribute or implementing IValidatableObject.

The ValidationAttribute allows you to add client side validation relatively simply by implementing IClientValidatable and registering a new adapter and method via jQuery. See Perform client side validation for custom attribute.

IValidatableObject is more suited to one-off validation requirements where reuse is not an option. It also results in slighlty simpler code. Unfortunately, there is no easy way to implement client side validation using this method.

like image 83
Paolo Moretti Avatar answered Sep 21 '22 22:09

Paolo Moretti