I’m trying to use jQuery validation plugin to validate a few form fields by using custom add.method, and I need some help with it.
Here is my html form.
<form method="post" action="<?=$PHP_SELF?>" name="sf" id="sf">
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" /><br />
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br />
</p>
</form>
Basically I’m trying a very basic rule to check if the Name field is not empty.
I’m trying following, Please let me know if it is correct?
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("name",function(value,element){
return this.optional(element) || (i.test(value) > 0);
},"Name is required");
$("#sf").validate({
rules: {
name: true,
},
});
});
</script>
I want to display the name error message in front of the Name field in the form. How I can do that? Thanks for any help.
If you just want to make a form element required, you should add a class
requiredon the element:This will automatically get picked up by validate.
If you’re doing this just to figure out how to add a custom rule, I’d recommend against using a rule called “name” (I had problems with it in a simple example). Here’s how you could add a custom rule that ensures “name” is only characters:
Note that inside the
rulesobject you have to specify another object (name) that defines the rules for that element.As for placing the error in a specific place, check out the
errorPlacementoption:Would place the error between the label and the
input.Here’s an example of the two in action: http://jsfiddle.net/andrewwhitaker/7xD2H/