The following HTML form successfully utilizes jQuery's form validation, displaying "This field is required" to the right of the form field if left blank, and "Please enter at least 2 characters" if fewer than 2 characters were entered. However, instead of the validation metadata being specified using the class and minlength attributes on the "cname" form input field, I'd like to use jQuery's "rules" API instead, where the rules are specified in the body of the validate function. Thanks in advance:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="/lib/js/jquery.js"></script>
<script src="/lib/js/jquery.validate.js"></script>
<script>
$(document).ready(function(){$("#commentForm").validate(
/*
rules/messages here
*/
);}
);
</script>
</head>
<body>
<form id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
rules: {
cname: {
required: true,
minlength: 2
}
},
messages: {
cname: {
required: "<li>Please enter a name.</li>",
minlength: "<li>Your name is not long enough.</li>"
}
}
The examples contained in this blog post do the trick.
$("#commentForm").validate({
rules: {
cname : { required : true, minlength: 2 }
}
});
Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With