0

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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

1 Comment

That looks to be very useful!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.