简体   繁体   English

jQuery表单验证-如果发生错误则阻止表单提交

[英]Jquery form validation - prevent form submission if there is an error

I am using a jquery plugin to validate my form. 我正在使用一个jQuery插件来验证我的表单。 I want to prevent the user from submitting the form if there are conditions not met with the validation. 如果某些条件不符合验证条件,我想阻止用户提交表单。 Here is a piece of code I used in validation 这是我在验证中使用的一段代码

      $(function() {
        $("#register-form").validate({
            rules: {
                OMNI_FIRSTNAME: {
                    required: true,
                    minlength: 2,
                    maxlength: 50
                },
                OMNI_LASTNAME: {
                    required: true,
                    minlength: 2,
                    maxlength: 50
                },  
            messages: {
                OMNI_FIRSTNAME: "Please enter first name",
                OMNI_FIRSTNAME: {
                    required: "Please provide firstname",
                    minlength: "Firstname must be at least 2 character long",
                    maxlength: "Firstname reached maximum length of 50 characters long" 
                },
                OMNI_LASTNAME: "Please enter last name",
                OMNI_LASTNAME: {
                    required: "Please provide lastname",
                    minlength: "Lastname must be at least 2 character long",
                    maxlength: "Lastname reached maximum length of 50 characters long"  
                },
            submitHandler: function(form) {
                form.submit();
            }
        });
      });

The code above outputs messages to my form whenever a condition is not met. 上面的代码在不满足任何条件时将消息输出到我的表单。 I have a submit button in my form $('#register-form') that posts the data entered from the input fields ( OMNI_FIRSTNAME , OMNI_LASTNAME ). 我在$('#register-form')表单中有一个提交按钮,用于提交从输入字段( OMNI_FIRSTNAMEOMNI_LASTNAME )输入的数据。 How will I integrate the two processes into one? 如何将这两个过程整合为一个? currently, I can still post data that did not meet my jquery validation. 目前,我仍然可以发布不符合我的jquery验证的数据。

Make following changes in your jquery code 在您的jquery代码中进行以下更改

submitHandler: function(form) {

    form.preventDefault();
    form.submit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM