JQuery form validation

Ok, my problem is that I have a form that I want to check fields with jquery, if the data is correct, I let the send continue, if not, I will disable the default behavior by returning false (I saw that in the tutorial, here )
so I used, since I said the jquery syntax, when the document is ready, I am registered for the button click event, the problem is that the code never runs. I used firebug but did not understand. nothing happens, so here is my code:

$('#submitBtn').click(function() { var password1 = $('#form_password').val(); var password2 = $('#form_password2').val(); if( password1 != password2) { alert("the two passwords are not equal."); } return false; //to disable the default behavior of the submit btn }); 
+4
source share
4 answers

The correct way to check for form submission is to check the submit form event, not the click button. Change this, and what you have should work, although now it always makes return false; , so the form will never be submitted. This should do it:

 $('#myform').submit(function() { var motPasse1 = $('#form_motPasse').val(); var motPasse2 = $('#form_motPasse2').val(); if(motPasse1 != motPasse2){ alert("Les deux mot de passe ne sont pas identiques"); return false; // cancel form submission if passwords don't match } return true; // return true if no errors }); 

Finally, I hope you do not keep an alert there for production purposes. :) There are many, much better ways to display user notifications than a warning. Check this question for some suggestions, although something like just a <div> error and damping in it is better than the ugly default browser warning window.

+6
source

Since you said you were using a form, you can bind to the submit event form:

 $('form#id').submit(function(){ // your validation code }); 
+2
source

You should see the jQuery Validation Plugin . It is supported by a member of the jQuery team, and this simplifies the client-side validation process.

+2
source

Your problem is that you always return false, it should look like this:

 $('#envoyerButton').click(function() { var motPasse1 = $('#form_motPasse').val(); var motPasse2 = $('#form_motPasse2').val(); if( motPasse1 != motPasse2) { alert("Les deux mot de passe ne sont pas identiques"); return false; } return true; }); 
0
source

Source: https://habr.com/ru/post/1285913/


All Articles