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?
You can check for field validity with ModelState.IsValidField method
<div class="targetDiv" @if (Html.ViewData.ModelState.IsValidField("StartDate"))
{
<text>style="display:none"</text>
}>
My content
</div>
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):
$("#myForm").validate();
if ($("#myForm").valid()) {
$("#targetDiv").css("display", "none");
}
else {
if ($("[id='MainModel.StartDate']").hasClass("input-validation-error") {
//note the strange ID selector above, that's because it's got a . in :)
$("#targetDiv").css("display", "block");
}
else {
$("#targetDiv").css("display", "none");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With