简体   繁体   中英

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. but error never showing.

Edit:

@Sparky suggested. I am updating my post. I am loading input box and anchor tag after DOM loaded. then I added validation rule for CompanyName control. And also checking validation in <a> click and it is false. but still error text is not showing.

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

$.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.

<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 .


The problem is caused by incorrectly calling the .validate() method inside of a function that's triggered on the click of the submit button.

The .validate() method is the initialization of the plugin and only gets called once on DOM ready.

The other problem is the location of your ajax() . The .ajax() only belongs inside the submitHandler option of the .validate() method .

$(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"...

<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...

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

Working DEMO: http://jsfiddle.net/3nsapjrh/


You do not need to put the novalidate="novalidate" attribute within your <form> tag. The plugin already dynamically does this for you.

Second answer: posted in response to edited 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. {form fully exists on the page now}

  3. Call .validate() to initialize the plugin on the newly created form. You would not need the .rules() method since you can declare the rules within .validate() at this point.

NOTES :

  • Once .validate() is called, you cannot call it again for any reason. You can only use rules() method to dynamically add/remove rules.

  • You would never need any inline JavaScript. Remove your onclick="javascript: submitcompanyfind();" and the submitcompanyfind() function.

  • When you're not using a type="submit" , you need to construct a simple click handler to trigger a .submit() . If the anchor tag does not yet exist when you call the click handler, you simply need to "delegate" it .

     $('#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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