Reputation: 7542
I am using the jquery validation plugin on an existing form but it isn't firing on submit.
I am not getting any javascript error in the browser but just nothing is happening and the form is submitting which is shouldn't.
Here is the code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js></script>
<script type="text/javascript">
$().ready(function () {
// validate the comment form when it is submitted
$("#registrationform").validate();
// validate signup form on keyup and submit
$("#registrationform").validate({
rules: {
fullname: {
required: true,
minlength: 2,
maxlength: 50
}
},
messages: {
fullname: {
required: "Please enter a name",
minlength: "Your name must consist of at least 2 characters",
maxlength: "Your name must consist of not more than characters"
}
}
});
});
</script>
</head>
<body>
<form id="registrationform" name="registrationform" method="post" action="pageaftervalidation.html">
<table>
<tr>
<td>Name:</td>
<td><input id="fullname" name="fullname" type="text"></td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
Why is it not firing any validation on submit?
Found the problem.
I cannot have two validate functions. From the demo I tried to validate the form both on submission and on keyup but I didn't need to as the keyup validation does both.
So to fix the above I remove the line
$("#registrationform").validate();
Upvotes: 0
Views: 1478
Reputation: 98748
It's not working because the first instance of .validate()
takes precedence over any subsequent instance. Since there are no options defined within your first instance, then plugin is initialized without any rules or options, and the second instance is completely ignored.
$("#registrationform").validate(); // <-- delete this line.
$("#registrationform").validate({
// your rules & options
});
Also, as per jQuery documentation, this is not recommended...
$().ready(function () {
Change it to something more standard...
$(document).ready(function () {
And for more efficient code, you can use the rangelength
method in place of minlength
and maxlength
.
minlength: 2,
maxlength: 50
can more simply be written as...
rangelength: [2,50]
Upvotes: 2