Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show div if unobtrusive validation was invalid and hide it if Valid in MVC 3

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?

like image 371
Saeid Avatar asked Dec 13 '22 03:12

Saeid


2 Answers

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>
like image 184
archil Avatar answered Jan 17 '23 13:01

archil


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");
    }
}
like image 43
mattytommo Avatar answered Jan 17 '23 14:01

mattytommo