Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
    });

});
like image 210
Erandi Avatar asked May 14 '14 14:05

Erandi


People also ask

How do you check if jQuery validate is working?

The plugin adds a validationPlugin function to jQuery. fn , so simply check whether it exists or not; if (typeof jQuery. fn.

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.


2 Answers

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/

like image 52
Sparky Avatar answered Sep 27 '22 21:09

Sparky


This is my solution including Greek characters.

$.validator.addMethod('alphabet', function (value, element) {

        let regExName = /^[A-Za-zΑ-Ωα-ωίϊΐόάέύϋΰήώ]+$/;
        return (regExName.test(value));

    }, 'There are non alphabetic characters!');
  $("#orderForm").validate({
     rules: {
          first_name: {
             required: true,
             alphabet: true
          }
});
like image 39
Apostolos Avatar answered Sep 27 '22 22:09

Apostolos