5

I Use Asp.Net MVC 2 with entity framework 4. Here is the situation : I Have a checkbox and a textbox(Date Picker). If the checkbox is checked, the textbox is required. If the checkbox is false, the textbox is not required.
Checkbox True => Textbox Required
Checkbox False => Textbox not required

<%:Html.CheckBoxFor(model => model.oEnvironment.Remediate) %>
<%= Html.TextBoxFor(model => model.oEnvironment.DatePick)%>

I know how to create a ValidationAttribute but I dont know how to create a validation class that verify if the checkbox is checked (if my Entity Remediate Attribute is true) and then put the DatePick field as required.

Any Idea ?

Jean-Francois
  • 1,899
  • 4
  • 35
  • 73

4 Answers4

2

If you don't need client validation, I suggest that you use ModeState.AddModelError to test your logic (in your controller).

Something like:

[HttpPost]
public ActionResult Edit(MyModel model)
{
        if (model.Remediate && string.IsNullOrEmpty(model.DatePick))
            ModelState.AddModelError("DatePickRequired", "DatePick is required");
        if (!ModelState.IsValid)
            return View(model);
        return View();
}

Gtz,
Stéphane.

Stéphane Bebrone
  • 2,713
  • 17
  • 18
0

You might be able to implement the IDataErrorInfo interface on your model, although I haven't ever tried this myself.

Ryan
  • 4,303
  • 3
  • 24
  • 24
0

As a totally different approach, you could take a look at the Fluent Validation project http://fluentvalidation.codeplex.com/ which plays well with MVC via an inversion of control container http://fluentvalidation.codeplex.com/wikipage?title=mvc&referringTitle=Documentation and http://www.jeremyskinner.co.uk/2010/02/22/using-fluentvalidation-with-an-ioc-container/

This should enable you to code this and similar rules really well, and the IOC articles show how to integrate into MVC<3

(not strictly an answer as you stated MVC2 but an upgrade to MVC3 would make this easier too as it supports model level validation http://www.asp.net/mvc/mvc3#BM_Model_Validation_Improvements )

Andiih
  • 12,285
  • 10
  • 57
  • 88
0

For complex validation, just perform the validation in the action (or anywhere on the server side).

Beep beep
  • 18,873
  • 12
  • 63
  • 78