Validate a form on Click event with validator jQuery

允我心安 提交于 2019-12-04 12:24:07

问题


I am using jQuery validate for validate an input. My code:

 $('#button').click( function() {       
    $("#form").validate({              
        rules: {
            phone: {
                required: true,
                number: true,
                rangelength: [7, 14]
            }
        }
    }); 
});

And the HTML:

<form id="form" name="form" method="post" action="">
 <input id="phone" name="phone" class="required" type="text" />
 <div class="button" id="send_b">Send</div>
 </form>

This code is not working. If I add this line of jQuery

$("#form").submit();  

inside the click event it works. But I don't want to submit the form so I want just to make the validation on click.

Does anyone know how to do this?


回答1:


Just add .form() to manually trigger the validation immediately (the default behavior waits for a submit event):

$('#button').click( function() {       
  $("#form").validate({              
    rules: {
      phone: {
        required: true,
        number: true,
        rangelength: [7, 14]
      }
    }
  }).form(); 
});



回答2:


Your code is binding a function to the click event of a button. What you're doing is saying "when this button is clicked, apply form validation to the form".

This is the incorrect way to use the validation plugin (I'm assuming you're using this validation plugin). Instead, you just execute the validation() method directly onto the form element; the plugin takes care of the submit event.

So, get rid of the click event binding.




回答3:


Use form method form() method with your click event



来源:https://stackoverflow.com/questions/7445423/validate-a-form-on-click-event-with-validator-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!