views:

27

answers:

4

Hi,

I am using EF4 and ASP.NET MVC 2 for my web application. I am also using data annotations for my validation.

Is the following possible? If so, how would I implement it? I have a checkbox, and a from and to date. The from and to date are not required fields, but when the checkbox is ticked then the from and to dates are required fields. Then the required error must display.

How is this possible?

Thanks.

A: 

You need to create a validation attribute for the model class itself that validates the three fields.

For an example, look at the [FieldsMustMatch] attribute in the default MVC project template.

SLaks
A: 

In the Controller where you check your ModelState you can check to see if the checkbox is checked before you call View()

[HttpPost]
public ActionResult Index(LoanData myObject) {

  //Your custom implementation
  if (!checkBox.Checked) {
    return View();
  }

  //Normal validation
  if (ModelState.IsValid) {
    return View("Index", myObject);
  } else {
    return View();
  }
}

This way you can control when you do validation based on if the checkbox is checked or not.

Robert Greiner
A: 

This is very similar to a question asked earlier today. It is not possible to create a property level custom attribute using DataAnnotations out of the box classes as you cannot access other property values of the parent class however it can be done by extending the framework a little.
See here for more detail and related link.

Andy Rose
+1  A: 

well, on property level contingent validations are hard to achieve in MVC. but u can extend the framework or u can use some other library to achieve the goal. i m using foolproof validation by nick successfully for contingent validations in my project. u can take a look at it here

Muhammad Adeel Zahid
That looks to be very useful!
KallDrexx