Reputation: 24488
I recently realized that one of my pages does not contain: $("#form1").validate(); call, however the page does a jquery validation on the 'required' fields.
I do have code at the bottom of the page:
<script type="text/javascript">
var originalDoPostBack = __doPostBack;
__doPostBack = function(sender, args) {
if ($("#form1").valid() === true) {
originalDoPostBack(sender, args);
}
};
</script>
My testing and viewing the source seems that that I do not need the $("#form1").validate() if I have $("#form1").valid().
Is this correct?
Upvotes: 0
Views: 609
Reputation: 337560
$.validate()
is used to set up the form and it's fields for validation. For example, to set the rules, such as required
and email
, and to define the messages to be displayed on errors. It also attaches to the submit
event of your form so that it automatically calls $("form").valid()
on form submit.
Example:
$("form").validate({
rules: {
Username: { required: true, email: true },
Password: { required: true }
},
messages: {
Username: {
required: "Please enter your username",
email: "Please enter a valid username"
},
Password: "Please enter your password"
}
});
<form>
<input type="text" id="Username" name="Username" />
<input type="text" id="Password" name="Password" />
</form>
Alternatively you can use classes for the rules, and the title
attribute on the fields for the error messages. Using this method you will need to manually call $("form").valid()
when the form is submit.
$("form").submit(function() {
return $(this).valid();
});
<form>
<input type="text" id="Username" name="Username" class="required email" title="Please enter your username" />
<input type="text" id="Password" name="Password" class="required" title="Please enter your password" />
</form>
It's worth noting that the first method gives you far more control over the appearance and settings of the form, and is also a better separation of concerns IMO. The only benefit of the latter is it's brevity.
Upvotes: 2