简体   繁体   English

添加规则后,jQuery表单验证不起作用

[英]jquery form validation not working after rule added

I have added rule for the control. 我为控件添加了规则。 but still error not showing after form validation. 但表单验证后仍未显示错误。 After click I have validate input box and check empty string. 单击后,我具有验证输入框并检查空字符串。 if empty string show error otherwise call ajax method. 如果空字符串显示错误,则调用ajax方法。 but error never showing. 但是错误永远不会显示。

Edit: 编辑:

@Sparky suggested. @Sparky建议。 I am updating my post. 我正在更新我的帖子。 I am loading input box and anchor tag after DOM loaded. DOM加载后,我正在加载输入框和锚标记。 then I added validation rule for CompanyName control. 然后我为CompanyName控件添加了验证规则。 And also checking validation in <a> click and it is false. 还要在<a>单击中检查验证,这是错误的。 but still error text is not showing. 但仍未显示错误文本。

html html

<form action="/Address/AddAddress" id="frmAddress" method="post" name="frmAddress" novalidate="novalidate">
   <div id="AddEditAddressPlaceHolder>
           <input name="CompanyName" class="SPE-Formcontrol" id="CompanyName" type="text" value="">

          <a href="#" class="btn btn-success" onclick="javascript: submitcompanyfind();">Find Company</a>

javascript javascript

$.ajax({
                url: 'AddressTypesListChange',
                type: "Get",
                data: { 'addressType': $("#AddressTypeslist").val()},
                cache: false,
                success: function(data) {
                    $('#AddEditAddressPlaceHolder').html(data);
                   $("#frmAddress").validate({
                        errorClass: "validationError"
                    });
                    $("#CompanyName").rules("add", {required: true,messages: {required: "Required"}});

                }
            });


 function submitcompanyfind() {
      $("#frmAddress").validate();
      alert($("#frmAddress").valid()); // it is false but no error showing.
     if ($('#CompanyName').val() !="") {
         $.ajax({
             url: 'FindCompanyList',
             type: 'Post',
             data: $("#frmAddress").serialize(),
             success: function(data) {
                 var count = Object.keys(data).length;
                 //load the company table rows
                 LoadCompanyList(data);

                 $("#hdnDivComapnyfinder").show();
             },
             error: function(xhr, ajaxOptions, thrownError) {

             }
         });
     }

 }

After page load html source looks like this. 页面加载后,html源代码如下所示。

<div id="AddEditAddressPlaceHolder">
        <input name="CompanyName" class="SPE-Formcontrol 
        input-validation-error" id="CompanyName" type="text" 
       value="" aria-required="true" 
       aria-describedby="CompanyName-error" aria-invalid="true">

    </div>

EDIT: the following answer was for the OP's original version of his question . 编辑:以下答案是针对OP的问题原始版本


The problem is caused by incorrectly calling the .validate() method inside of a function that's triggered on the click of the submit button. 该问题是由于在单击提交按钮时触发的函数内部错误地调用了.validate()方法引起的。

The .validate() method is the initialization of the plugin and only gets called once on DOM ready. .validate()方法是插件的初始化,仅在DOM准备就绪时被调用一次。

The other problem is the location of your ajax() . 另一个问题是ajax()的位置。 The .ajax() only belongs inside the submitHandler option of the .validate() method . .ajax()仅属于submitHandler .validate()方法的submitHandler选项内

$(document).ready(function() {

    $("#frmAddress").validate({
         rules: {
             CompanyName: {
                 required: true
             }
         },
         messages: {
             CompanyName: {
                 required: "Required"
             }
         },
         errorClass: "validationError",
         submitHandler: function(form) {
             // your ajax function here,
             return false;
         }
     });

});

Don't forget to remove your inline JavaScript from the "submit button"... 不要忘记从“提交按钮”中删除您的内联JavaScript。

<a href="#" class="btn btn-success">Find Company</a>

Ans since you're using an anchor tag instead of a real type="submit" button or input , you'll need to write a click handler function that triggers validation by programmatically calling submit... Ans,因为您使用的是锚标记而不是实际的type="submit" buttoninput ,所以您需要编写click处理程序函数,该函数可通过以编程方式调用commit来触发验证...

$('#frmAddress a').on('click', function() {
    $('#frmAddress').submit();
});

Working DEMO: http://jsfiddle.net/3nsapjrh/ 工作演示: http//jsfiddle.net/3nsapjrh/


You do not need to put the novalidate="novalidate" attribute within your <form> tag. 您无需将novalidate="novalidate"属性放在<form>标记内。 The plugin already dynamically does this for you. 该插件已经为您动态地完成了此任务。

Second answer: posted in response to edited OP. 第二个答案:发布以响应编辑的OP。

I'm not going to include specific code to a question that has been changed so radically since it was originally posted. 自最初发布以来,问题已经发生了如此大的变化,我将不包含特定的代码。 Instead, I'll review the critical points that need to be followed in this situation... 相反,我将回顾这种情况下需要遵循的关键点...

  1. Load the page, including the relevant plugins. 加载页面,包括相关的插件。

  2. Trigger the ajax() that loads and/or creates the form and/or all of its input fields. 触发ajax()来加载和/或创建表单和/或其所有输入字段。 {form fully exists on the page now} {表格现已完全存在于页面上}

  3. Call .validate() to initialize the plugin on the newly created form. 调用.validate()在新创建的表单上初始化插件。 You would not need the .rules() method since you can declare the rules within .validate() at this point. 你不会需要.rules()方法,因为你可以声明在规则之内.validate()在这一点上。

NOTES : 注意事项

  • Once .validate() is called, you cannot call it again for any reason. 调用.validate() ,由于任何原因都无法再次调用它。 You can only use rules() method to dynamically add/remove rules. 您只能使用rules()方法动态添加/删除规则。

  • You would never need any inline JavaScript. 您将不需要任何内联JavaScript。 Remove your onclick="javascript: submitcompanyfind();" 删除您的onclick="javascript: submitcompanyfind();" and the submitcompanyfind() function. submitcompanyfind()函数。

  • When you're not using a type="submit" , you need to construct a simple click handler to trigger a .submit() . 当您不使用type="submit" ,您需要构造一个简单的click处理程序来触发.submit() If the anchor tag does not yet exist when you call the click handler, you simply need to "delegate" it . 如果在调用click处理程序时anchor标签尚不存在,则只需“删除”它

     $('#frmAddress').on('click', 'a', function() { $(this).submit(); }); 
  • If you're submitting the form with ajax() , then you must put that ajax() function within the submitHandler option of the .validate() method. 如果要使用ajax()提交表单,则必须将该ajax()函数submitHandler .validate()方法submitHandler选项中。

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

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