<!DOCTYPE htm开发者_运维技巧l PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validation POC</title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#frm").validate({
rules: {
cname: {
required: true
},
cemail: {
required: true,
email: true
}
},
messages: {
cname: "Please
enter
your
name",
cemail: {
"Email
is
not
validated"
}
}
});
});
</script>
</head>
<body>
<form id="frm" action="" method="get">
<fieldset>
<legend>Validation POC</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" />
</p>
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email"size="25" />
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
I am trying to do form validation using jquery validation. I am trying to give my own error messages. But this code is not running.
When I tried
<input type="text" id="cemail" class="required"></input>
the code is working fine, but with this , I am not able to give custom error messages. Please let me know if I am doing something wrong in upper code.
EDIT: I have another concern as well , if validation fails for any control, I want to change the background color of that control. And I also want to remove the default error message.There are 2 issues, mainly you need to use the name
attribute (not the id
attribute), so name
and email
, not cname
and cemail
for your rules. Also, the {}
around the email
error message needs removing. Overall you want to look like this:
$("#frm").validate({
rules: {
name: { required: true },
email: { required: true, email: true }
},
messages: {
name: "Please enter your name",
email: "Email is not validated"
}
});
You can give it a try here.
cemail and cname should be added to input elements as class, not ID.
example:
<input class="cemail" name="email" size="25" />
format should be like this...
$(document).ready(function() {
$("#frm").validate({
rules: {
cname: {
required: true
},
cemail: {
required: true,
email: true
}
},
messages: {
cname: {
required: "Please enter your name"
},
cemail: {
email: "Email is not validated"
}
}
});
});
cname
and cemail
are the values of name
attribute of the input
.
精彩评论