user966582
user966582

Reputation: 3323

jQuery Validation Plugin addMethod

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.

Upvotes: 4

Views: 9309

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

If you just want to make a form element required, you should add a class required on the element:

<input type="text" name="name"  id="name" class="required" />

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:

$.validator.addMethod("customname", function(value, element) {
    var i = /^[A-Za-z]+$/;
    return this.optional(element) || (i.test(value) > 0);
}, "Name is required");

$("#sf").validate({
    rules: {
        name: {
            customname: true
        }
    }
});

Note that inside the rules object 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 errorPlacement option:

errorPlacement: function(error, element) {
    element.closest("p").prepend(error);
}

Would place the error between the label and the input.

Here's an example of the two in action: http://jsfiddle.net/andrewwhitaker/7xD2H/

Upvotes: 6

jamesmortensen
jamesmortensen

Reputation: 34078

This will accomplish what you are trying to do:

 $(document).ready( function() {
     $('#sf').validate();
     $("#name").rules("add", {
         required: true,
         minlength: 0,
         messages: {
             required: "Name is required"               
         }
     });
 });

Upvotes: 0

Related Questions