This is a part of my Edit view:
<dt>
@Html.LabelFor(model => model.MainModel.StartDate)
</dt>
<dd>
@Html.TextBoxFor(model => model.MainModel.StartDate)
@Html.ValidationMessageFor(model => model.MainModel.StartDate)
<div class="targetDiv"> My content </div>
</dd>
So as all of you know when StartDate
field in my model not valid unobtrusive show the error message and if valid hide it. Now I want to add another action to this process. I need if StartDate
value is Invalid show "targetDiv" div
and if StartDate
value is Valid hide it. what is your suggestion?
Unobtrusive validation adds a css classes to your validation element and that's how it determines will it show or hide the validation message. Here's an examle:
This is how your html will look in the source. After you write invalid data in the StartDate input it will look slightly different notice the classes added to your input and to the span element:
You can check if span element has a field-validation-error class and show your targetDiv. I mimicked how unobtrusive validation works and provided the working sample:
In the real world example you just need to use:
Here's the jsFiddle: http://jsfiddle.net/mgrcic/Zj6zS/
Regards.
You'll have to first validate your form (assuming it's got an id of myForm and the following code is wrapped inside a save button click function):
You can check for field validity with ModelState.IsValidField method