jQuery form validation on button click
Solution 1:
Within your click
handler, the mistake is the .validate()
method; it only initializes the plugin, it does not validate the form
.
To eliminate the need to have a submit
button within the form
, use .valid()
to trigger a validation check...
$('#btn').on('click', function() {
$("#form1").valid();
});
jsFiddle Demo
.validate()
- to initialize the plugin (with options) once on DOM ready.
.valid()
- to check validation state (boolean value) or to trigger a validation test on the form
at any time.
Otherwise, if you had a type="submit"
button within the form
container, you would not need a special click
handler and the .valid()
method, as the plugin would capture that automatically.
Demo without click
handler
EDIT:
You also have two issues within your HTML...
<input id="field1" type="text" class="required">
You don't need
class="required"
when declaring rules within.validate()
. It's redundant and superfluous.The
name
attribute is missing. Rules are declared within.validate()
by theirname
. The plugin depends upon uniquename
attributes to keep track of the inputs.
Should be...
<input name="field1" id="field1" type="text" />
Solution 2:
$(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.