1

I am trying to override the functionality of 'required' and 'minlength' validators provided by jQuery Validator plugin. Following is my code:

jQuery(".form-cls").validate({
             errorElement: "span",
             errorClass: "error-msg",
        rules: {
            email:{
                required:true,
                email:true,
                alreadyExistEmail: true
            },
            user_email:{
                required:true,
                email:true
            },
            password:{
                required: function (element) {
                                    return checkIfPasswordIsRequired();
                                },
                                minlength: function (element) {
                                  return passwordLengthCheck(element);  
                                }
                    }
        }
    });

function checkIfPasswordIsRequired()
    {
        if(jQuery("#facebook_id").length > 0 || jQuery("#linkedin_id").length > 0 || jQuery("#xing_id").length > 0) {
            if(jQuery("#facebook_id").val() != "" || jQuery("#linkedin_id").val() != "" || jQuery("#xing_id").val() != "") {
                return false;
            }
        }
        return true;
    }





function passwordLengthCheck(element)
    {
        if(element.value.length < 6)
        {
          return false;
        }
        else
        {
          return true;
        }
    }

Now here the first check on password field is working fine that is of 'required' but the second check is not working. If have checked it my console.log(element.value.length) and it gives the length of value in password field each time the value is changed/altered but depending on the condition in function passwordLengthCheck it never shows/displays error. Kindly help!!

Muhammad Raza
  • 424
  • 5
  • 22

1 Answers1

1

To check field length, just add minlength attribute to the <input> tag, like

<input id="pw" name="pw" minlength="6" type="password">

To add some custom validation, use addMethod():

jQuery.validator.addMethod("func", function(value, element) {
  return this.optional(element) || check expression here;
}
Bandon
  • 809
  • 1
  • 6
  • 14
  • Can you please explain a little more? im also stuck in same problem where my project is very large and running validate centralized method, i want to override that code and want to run my customize validate method. – Hasan Badshah Apr 26 '20 at 00:43