Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show div if validation fails

I want this div to show if the form validation is unsuccessful.

<div class="alert">
  <strong>Warning!</strong> @Html.ValidationSummary(false, "Fix these errors:")
</div>

I tried to wrapped it inside

if(! ViewData.ModelState.IsValid)

but div is not displayed when submitting the form. Probably because there is not post back due jquery validation. The validation logic seems alright, if i remove the if-statement validation summary list all incorrect input fields.

How can I toggle the visibility of the div based on the validation?

like image 786
dbd Avatar asked Oct 24 '12 09:10

dbd


2 Answers

Update

I rewrote the accepted answer. If the server connection is slow the error div will be visible during the server request. Even if there is no errors. I changed it to check if the form is valid when submitting the form. This code snippet assumes you have one form.

$(document).ready(function () {
    $(".alert").hide(); //hides the div on page load

    $("form").submit(function () {
        if (!$(this).valid()) {
            $('.alert').show();
        }
    });        
}); 
like image 87
dbd Avatar answered Sep 30 '22 19:09

dbd


You can apply this simple script. It's not very sophisticated, but it should do the trick

$(document).ready(function () {
    $('.alert').hide(); //hides the div on page load
    $('#submit').click(function () {  //assumes your submit button has id="submit"
        $('.alert').show(); //shows the div when submit is clicked
    });
});

As you can see, this doesn't actually care about the validation. It simply makes the 'alert' div visible when the submit button is clicked. If there are validation errors, the div will show with your warnings. If the form is valid, I'm assuming a refresh, or redirect, so the div will never actually have a chance to show.

like image 45
Forty-Two Avatar answered Sep 30 '22 18:09

Forty-Two