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?
Within your
clickhandler, the mistake is the.validate()method; it only initializes the plugin, it does not validate theform.To eliminate the need to have a
submitbutton within theform, use.valid()to trigger a validation check…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 theformat any time.Otherwise, if you had a
type="submit"button within theformcontainer, you would not need a specialclickhandler and the.valid()method, as the plugin would capture that automatically.Demo without
clickhandlerEDIT:
You also have two issues within your HTML…
You don’t need
class="required"when declaring rules within.validate(). It’s redundant and superfluous.The
nameattribute is missing. Rules are declared within.validate()by theirname. The plugin depends upon uniquenameattributes to keep track of the inputs.Should be…