I’m trying to use jquery validation with a rule/message set and can’t seem to get it working. Relativeny new to JQuery, so apologies if it’s a basic question. I’m trying to use document.forms[0] instead of a form ID. It works with simple validation where the field has class=”required” but not if I try to introduce rules. Any help greatly appreciated. Here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery- validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$(document.forms[0]).validate({
rules: {
cname: {
required: true,
}
},
messages: {
cname: "Please enter a valid Name."
},
});
});
</script>
</head>
<body>
<form class="cmxform" 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"/>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
Firstly, you can just target your form by its
id,#commentForm. Secondly, the root cause of your problem was that you were improperly targeting theinputfield by itsidattribute. However, the.validate()plugin is looking for thenameattribute, which in your case, also happened to be"name". I’ve changed the value of thenameattribute in my example below just to make it more clear.jQuery:
HTML:
Working DEMO:
http://jsfiddle.net/egdEn/
See the online documentation for more info.