jqueryjquery-validate

Use addMethod in jQuery Validate plugin


I want to validate a text box using jQuery Validate plugin's custom validation method (addMethod) but my code doesn't work. Can anyone help me to find the error? I have never used custom validation method before so it's bit hard for me to find where I went wrong in this code.

This is my code:

$(document).ready(function () {

jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod(
"selectnic"
function(value,element){
if(element.value == /^[0-9]{9}[vVxX]$/)
   return false;
   else return true;
},
"wrong nic number"
); 



    $('#basicDetails').validate({ // initialize the Plugin
        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                },
                lname: {
                    required: true,
                    lettersonly: true,
                },  
            },
        messages: {
           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",  
            },
        },
        submitHandler: function (form) { 
            alert('valid form submitted'); 
            return false; 
        }
    });

});

..html code ....

<form action="#" method="post"  id="basicDetails" runat="server">

 <table width="68%" border="0" cellpadding="6" cellspacing="6">


 <tr>
                                    <td>&nbsp;</td>
                                    <td> First name </td>
                                    <td>:</td>
                                    <td><input type="text" name="fname" id="fname" class="textbox" placeholder="Required field"/><div class="myErrors"></div></td> &nbsp;
                                    <td align="right"> Last name&nbsp; :</td>
                                    <td><input type="text" name="lname" class="textbox" id="lname" placeholder="Required field"/><div class="myErrors"></div></td>
                                </tr>

                                <tr>
                                    <td>&nbsp;</td>
                                    <td width="147" > NIC no </td>
                                    <td> : </td>
                                    <td width="172"><input type="text" name="nic" id="nic"   class="textbox"  placeholder="Required field"/><div class="myErrors"></div></td>
                                    <td width="167" align="right">Passport no &nbsp; :</td>
                                    <td width="167" id="showPP"> <input type="text" name="passport" class="textbox" id="ppnu" placeholder="Required field"/></td>    
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td colspan="3"><input type="submit" name="submit"  value="Submit "class="submit"   id="submit" />&nbsp; &nbsp;
                                    <input type="submit" name="reset"  value="Reset "class="reset" />
                                    </td>                                
                                </tr>


 </table>





</form>

.....after editing my code ....

$(document).ready(function () {



jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;
    } else {
        return true;
    };
}, "wrong nic number"); 


    $('#basicDetails').validate({ // initialize the Plugin


        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                        },
                lname: {
                    required: true,
                    lettersonly: true,
                    },

                 nicnumber: {
                            // other rules,
                        selectnic: true // <-  declare the rule someplace!
                            }


            },


        messages: {

           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",

            },
        },


        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});

Solution

  • There are three different issues as outlined by the progressing edits below.


    1) You missed a comma just between selectnic and the function(.

    Also, try this format instead when using regex...

    jQuery.validator.addMethod("selectnic", function(value, element){
        if (/^[0-9]{9}[vVxX]$/.test(value)) {
            return false;  // FAIL validation when REGEX matches
        } else {
            return true;   // PASS validation otherwise
        };
    }, "wrong nic number"); 
    

    EDIT: This answer assumes your original regex and logic are both correct. Your logic returns false when the regex is a match. false means that validation failed and you will see the error message.


    2) EDIT 2:

    After creating new methods, you also have to use them. I do not see the selectnic rule/method used anyplace in your code.

    Example:

    rules: {
        myFieldName: {
            // other rules,
            selectnic: true // <-  declare the rule someplace!
        }
    }
    

    3) EDIT 3:

    And finally, the OP's original true/false logic was backwards. He wanted to PASS validation upon a regex match… therefore, needs to return true.

        if (/^[0-9]{9}[vVxX]$/.test(value)) {
            return true;   // PASS validation when REGEX matches
        } else {
            return false;  // FAIL validation
        };
    

    DEMO: http://jsfiddle.net/DzvNr/