Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Model Validation based on two properties. One influence the other one

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 ?

like image 405
Jean-Francois Avatar asked Nov 05 '22 01:11

Jean-Francois


1 Answers

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.

like image 92
Stéphane Bebrone Avatar answered Nov 09 '22 06:11

Stéphane Bebrone