UPDATE:
my question is more about How to prevent the form submit if the validation fails
the link does not solve my problem
just re-iterate what I'm doing:
I have a form with bunch of input fields and when the user hit the submit button it validate form using attribute required="required"
if the form validation fails THEN I want to stop submitting the form as you see the javascript it show the div when the user submit the form.
Hope this clears up.
END UPDATE
How can I stop the form submit to fire if the form validation fails?
<input class="form-control" data-val="true" id="SerialNumber" name="SerialNumber" required="required" type="text">
<button type="submit" name="rsubmit" class="btn btn-success">Submit</button>
//loading message:
$("form").submit(function (e) {
$("#loading").show();
});
Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.
To disable just the submit button(s), you could do this: $('button[type=submit], input[type=submit]'). prop('disabled',true);
Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
You need to do two things if validation fails, e.preventDefault() and to return false.
For your example, with the input given, the pseudo code might be the next:
$("form").submit(function (e) {
var validationFailed = false;
// do your validation here ...
if (validationFailed) {
e.preventDefault();
return false;
}
});
I able to fixed the problem:
First add the ref on your page:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
then do this check:
$("form").submit(function () {
if ($(this).valid()) { //<<< I was missing this check
$("#loading").show();
}
});
Write your validation code on onsubmit handler of your form like this
<form onsubmit="return Validation()">
<input class="form-control" data-val="true" id="SerialNumber" name="SerialNumber" required="required" type="text">
<button type="submit" name="rsubmit" class="btn btn-success">Submit</button>
<script>
function Validation(){
//Do all your validation here
//Return true if validation is successful, false if not successful
//It will not submit in case of false.
return true or false;
}
</script>
</form>
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