20

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

});
6
  • Where is the HTML markup for this form? Commented May 14, 2014 at 14:57
  • 1
    I can see a syntax error, you have missed , after selectnic. Also what's the point of comparing a string to a regex? Commented May 14, 2014 at 14:59
  • @ Sparky html code is bit long to add here Commented May 14, 2014 at 15:00
  • 1
    I did not say to add all of the HTML markup. Only add the relevant parts of the form… the opening/closing form tags and all of the input elements including the button. Commented May 14, 2014 at 15:01
  • @ Sparky I added my code Commented May 14, 2014 at 15:06

3 Answers 3

52

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/

Sign up to request clarification or add additional context in comments.

8 Comments

@Erandi, simply saying "it didn't work" is incredibly unhelpful to everyone. What didn't work? What troubleshooting did you perform? What errors are showing in your console? Are you sure your regex is correct? Is your logic correct? Your function will return false (FAIL validation) when the regex IS a match.
@ Sparky regex is correct here what I want is when user enter a NIC number it checks whether entered number has '804567789V' format (9 numbers and last letter can be 'x' or 'y' ) and using normal jQuery validation plugin I can't do this so I used custom validation method but here after adding this code I tried but it doesn't show any error message
@Erandi, you defined your new rule but you don't use it anyplace. How is the plugin supposed to know which input to evaluate your "selectnic" method? See my latest edit above.
@Erandi, seriously? I guess you didn't try it. It says "EXAMPLE", so yes, myFieldName means that you would insert your own field name.
@Erandi, please just slow down a bit in the future and read this site's FAQ sections. My very first comment above specifically asked you if the true/false logic was backwards and I even made comments in the code explaining that it would fail validation when the regex matched. Anyway, glad I could help.
|
1

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

Comments

-2
    jQuery.validator.addMethod("weekText",function(a,b){
        
        //return a=a.replace(/\s+/g,""),this.optional(b)||a.length>9&&a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/)
        //return a=a.replace(/\s+/g,""),this.optional(b)||a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        let result = a.match(/^(\+?61-?)/);
        let result1 = a.match(/^(\+?4-?)/);
        if(result == "+61,+61")
        {
            return true;
            //alert("dsdsfsf");
            //return a=a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        }
        else if(result == "+4,+4")
        {
            return true;
            //alert("Here1");
            //return a=a.match(/^(\+?04-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        }
        else
        {
            return false;
        }
        
    },"Please specify a valid phone number");
var wh = jQuery("#footerform").validate({
    rules: {
    'fullname':{
    required:true
    },
    
    'footer-email':{
    required: true,
    email:true
    },
    'footer-phone':{
    required:true,
    //phoneAu: true,
    //rangelength : [5, 16],
    weekText: true
    },
    'footer-address':{
    required:true,
    lettersonly: true
    },
    'footer-message':{
    lettersonly: true
    }
  },
  messages: {
    'fullname': {
    required: "Please enter your name."
    },
    
    'footer-email': {
    required: "Please enter your email.",
    email: "Please enter valid email address."
    },
    'footer-phone' : {
    required: "Please enter your phone.",
    //rangelength : "Please enter valid phone number.",
     weekText : "Please specify a valid phone number"
    },
    'footer-address': {
    required: "Please enter your address.",
    lettersonly: "Please enter Letter Only.",
    },
    'footer-message':{
    lettersonly: "Please enter Letter Only.",
    }
  },
  errorPlacement: function(error, element)
  {
  error.insertAfter( element );
  },
  errorElement: "label",
  errorClass: "error"
});
jQuery('#footerform .submit_btn_box').on('click', function(event) {
if (wh.form())
{
/*var response = jQuery('#g-recaptcha-response').val();
  if(response.length == 0  )
  {
    jQuery('#contactform .recaptcha-error-message').show();
    return false;
  }
  else
  {
    jQuery('#contactform .recaptcha-error-message').hide();
  } */          
}
else
{
  /*var response = jQuery('#g-recaptcha-response').val();
  if(response.length==0  )
  {
  jQuery('#contactform .recaptcha-error-message').show();
  return false;
  }
  else
  {
  jQuery('#contactform .recaptcha-error-message').hide();
  }*/
  event.preventDefault();
  event.stopPropagation();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.