[jquery] jQuery form validation on button click

I have a simple page with a form and a button outside the form. I am trying to validate the form on the button click. I have added the rules for validation of the form on the document.onready function. However the form is not getting validated.

HTML:-

<html>
<head>
   <script src="lib/jquery1.5.2.js"></script>
   <script src="lib/jquery.validate.js"></script>
   <script src="lib/myjs.js"></script>
</head>
<body>

<form id="form1" name="form1"> 
     Field 1: <input id="field1" type="text" class="required">
</form>

<div>
    <input id="btn" type="button" value="Validate">
</div>

</body>
</html>

JS:-

$(document).ready(function(){

$("#form1").validate({
   rules: {
     field1: "required"
   },
   messages: {
     field1: "Please specify your name"

   }
})

$('#btn').click(function() {
 $("#form1").validate();  // This is not working and is not validating the form
});

});

Any idea what's wrong?

This question is related to jquery jquery-validate

The answer is


$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.


You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button