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?
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();
}
});
});
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.
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