JQuery form validation

后端 未结 4 1563
梦毁少年i
梦毁少年i 2020-12-19 17:05

well my problem is that, i have a form, which i want to validate the fields using jquery, if the data is correct i let the submit continue, if no i disable the default behav

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 17:45

    The proper way of checking a form submission is to check the form's submit event, not the button's click event. Change that around and what you have should work, although as it is right now it is always doing return false; so the form would never be sent. 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 are not keeping the alert there for production purposes. :) There are much, much better ways to display user notifications than an alert. Check out this question for some suggestions, although something as simply as having an error

    and fading it in is nicer than the ugly default browser alert box.

提交回复
热议问题