26

I've got a little problem with my password-checker.

There's got a registration form with some fields. I use jQuery Validate plugin to validate user-inputs.

It all works except the password-validation:

The password should meet some minimum requirements:

  • minimum length: 8 -> I just use 'minlength: 8'
  • at least one lower-case character
  • at least one digit
  • Allowed Characters: A-Z a-z 0-9 @ * _ - . !

At the moment I use this code to validate the password:

$.validator.addMethod("pwcheck",
function(value, element) {
   return /^[A-Za-z0-9\d=!\-@._*]+$/.test(value);
});

This Code works for the allowed characters but not for minimum requirements. I know that you can use for example (?=.*[a-z]) for a lower-case-requirement. But I just don't get it to work.

If I add (?=.*[a-z]) the whole code doesn't work anymore. I need to know how to properly add the code to the existing one.

Thank you for your answers!

This is the complete code

<script>
                $(function() {
                    $("#regform").validate({
                        rules: {
                            forename: {
                                required: true
                            },
                            surname: {
                                required: true
                            },
                            username: {
                                required: true
                            },
                            password: {
                                required: true,
                                pwcheck: true,
                                minlength: 8
                            },
                            password2: {
                                required: true,
                                equalTo: "#password"
                            },
                            mail1: {
                                required: true,
                                email: true
                            },
                            mail2: {
                                required: true,
                                equalTo: "#mail1"
                            }
                        },
                        messages: {
                            forename: {
                                required: "Vornamen angeben"
                            },
                            surname: {
                                required: "Nachnamen angeben"
                            },
                            username: {
                                required: "Usernamen angeben"
                            },
                            password: {
                                required: "Passwort angeben",
                                pwcheck: "Das Passwort entspricht nicht den Kriterien!",
                                minlength: "Das Passwort entspricht nicht den Kriterien!"
                            },
                            password2: {
                                required: "Passwort wiederholen",
                                equalTo: "Die Passwörter stimmen nicht überein"
                            },
                            mail1: {
                                required: "Mail-Adresse angeben",
                                email: "ungültiges Mail-Format"
                            },
                            mail2: {
                                required: "Mail-Adresse wiederholen",
                                equalTo: "Die Mail-Adressen stimmen nicht überein"
                            }
                        }
                    });

                    $.validator.addMethod("pwcheck",
                        function(value, element) {
                            return /^[A-Za-z0-9\d=!\-@._*]+$/.test(value);
                    });
                });
                </script>
bayerphi
  • 325
  • 1
  • 4
  • 12
  • Show the rest of the code. Where is your `.validate()` call? Where is the HTML markup of the form? – Sparky Sep 11 '13 at 16:29
  • Where did you add the lookahead? Show us the code you tried not your working version. – Bergi Sep 11 '13 at 16:35
  • I added it almost everywhere. At least 20 different positions. I don't have all the code anymore... Have to say that I'm very new to this. So please excuse me. I'm sure it's just a bracket or something like that I forgot. – bayerphi Sep 11 '13 at 16:42
  • 1
    `/^(?=.*[a-z])[A-Za-z0-9\d=!\-@._*]+$/` should have done it. Did you try that? If so, how did it fail? – Bergi Sep 11 '13 at 16:43
  • Bergi, Thanks! Works like a charm! Don't how I couldn't get this done... Sometimes you just miss the forest for the trees. Anyway thanks a lot! – bayerphi Sep 11 '13 at 16:53

9 Answers9

47

If I add (?=.*[a-z]) the whole code doesn't work anymore.

Add it here:

/^(?=.*[a-z])[A-Za-z0-9\d=!\-@._*]+$/

However, it's much easier to do this without a lookahead:

$.validator.addMethod("pwcheck", function(value) {
   return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
       && /[a-z]/.test(value) // has a lowercase letter
       && /\d/.test(value) // has a digit
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Hello there, how about having at least one Uppercase Letter and at least one Special Character (eg. # $ % ' ^ , ( ) * + . : | = ? @ / ] [ _ ` { } \ ! ; - ~) – Yves Dec 01 '17 at 06:35
  • @Yves /[A-Z].test(value) // has an uppercase letter && /[=!\-@._*]/.test(value) expand the last one with extra characters, but be sure to include them in the first pattern or your string will invalidate before you can check if the special character is present. – hepabolu Jan 28 '18 at 13:05
  • how to give warning message to this method. That what to show when this format not match. – Love Pandey Jul 26 '19 at 11:10
  • @LovePandey See the jQuery-Validate documentation or the example in the question – Bergi Jul 26 '19 at 13:24
9

You can create your own custom jQuery validation rule. which returns a valid message for all the conditions with 100% accuracy.

$.validator.addMethod("strong_password", function (value, element) {
    let password = value;
    if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@#$%&])(.{8,20}$)/.test(password))) {
        return false;
    }
    return true;
}, function (value, element) {
    let password = $(element).val();
    if (!(/^(.{8,20}$)/.test(password))) {
        return 'Password must be between 8 to 20 characters long.';
    }
    else if (!(/^(?=.*[A-Z])/.test(password))) {
        return 'Password must contain at least one uppercase.';
    }
    else if (!(/^(?=.*[a-z])/.test(password))) {
        return 'Password must contain at least one lowercase.';
    }
    else if (!(/^(?=.*[0-9])/.test(password))) {
        return 'Password must contain at least one digit.';
    }
    else if (!(/^(?=.*[@#$%&])/.test(password))) {
        return "Password must contain special characters from @#$%&.";
    }
    return false;
});
Ketan Chaudhari
  • 329
  • 3
  • 7
3

Well you can use {8,} instead of "+" for a minimum of 8 chars with no maximum or better yet a {8, 20} for a minimum of 8 and a maximum of 20.

Really though I don't see the value in trying to squeeze all of your validation into a single regexp. If you break it up it makes it much easier to maintain, less bug prone, and it enables you to report back to the user the specific reason WHY the password failed instead of the entire requirement.

You could break it up into a few checks

//proper length
value.length >= 8 
//only allowed characters
/^[A-Za-z0-9\d=!\-@._*]+$/.test(value) 
//has a digit
/\d/.test(value)
//has a lowercase letter
/[a-z]/.test(value)

I'm not familiar with the jQuery Validation plugin, but I assume you could then return helpful a helpful message for each test that failed.

Anon
  • 51
  • 1
1

Try this:

jQuery.validator.addMethod("validate_password", function(value, element) {
  if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/.test(value)) {
    return true;
  } else {
    return false;
  }
}, "Please enter valid Password");
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

if you want to check confirm password and minimum character validation, then you can use

<input type="password" id="password" name="password"  class="validate[required,minSize[8]]"/>
<input type="password" id="confirm_password" name="confirm_password"  class="validate[required,equals[password]]"/>
Sandeep Sherpur
  • 2,418
  • 25
  • 27
0

Password validation can use several rules, for example:

var _validatePassword = function (validateUserNameRules, inputModel)
    {
        //bolean parameter validateUserNameRules -> true/false

        //this method recive a model like this:
        //inputModel.userName -> string
        //inputModel.password -> string
        //inputModel.password2 -> String

        var ResultModel = {
            ResultId: 1, //1 success
            Message: "Password is correct."
            };

        if (validateUserNameRules && inputModel.userName == "") {

            ResultModel.ResultId = 2;
            ResultModel.Message = "Error: User name cannot be blank.";
            return (ResultModel);
        }

        var re = /^\w+$/;
        if (validateUserNameRules && !re.test(inputModel.userName)) {

            ResultModel.ResultId = 2;
            ResultModel.Message = "Error: Username must contain only letters, numbers and underscores.";
            return (ResultModel);

        }

        if (inputModel.password != "" && inputModel.password == inputModel.password2) {
            if (inputModel.password.length < 6) {
                ResultModel.ResultId = 2;
                ResultModel.Message = "Error: Password must contain at least six characters.";
                return (ResultModel);
            }
            if (validateUserNameRules && inputModel.password == inputModel.userName) {
                ResultModel.ResultId = 2;
                ResultModel.Message = "Error: Password must be different from the Account Name.";
                return (ResultModel);
            }
            re = /[0-9]/;
            if (!re.test(inputModel.password)) {
                ResultModel.ResultId = 2;
                ResultModel.Message = "Error: Password must contain at least one number (0-9).";
                return (ResultModel);
            }
            re = /[a-z]/;
            if (!re.test(inputModel.password)) {

                ResultModel.ResultId = 2;
                ResultModel.Message = "Error: Password must contain at least one lowercase letter (a-z).";
                return (ResultModel);

            }
            re = /[A-Z]/;
            if (!re.test(inputModel.password)) {

                ResultModel.ResultId = 2;
                ResultModel.Message = "Error: Password must contain at least one uppercase letter (A-Z).";
                return (ResultModel);
            }
        } else {
            ResultModel.ResultId = 2;
            ResultModel.Message = "Error: Please check that you've entered and confirmed your password.";
            return (ResultModel);
        }

        return (ResultModel); //success password validation!!
    };
David Castro
  • 1,773
  • 21
  • 21
0

If you use ValidationEngine then you can use this

    "password": {
                    "regex": /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{6,30}$/, // /^[A-Za-z0-9\d=!\-@._*]*$/i
                    "alertText": "* Invalid Password, <br/>"
                            + "   1] Min 1 uppercase letter.<br/>"
                            + "   2] Min 1 lowercase letter.<br/>"
                            + "   3] Min 1 special character.<br/>"
                            + "   4] Min 1 number."
                },

Add this code in jquery.validationEngine-en.js file

Then use

 class="validate[required,custom[password],minSize[6],maxSize[30]]"

in Text Box class

Monzur
  • 1,341
  • 14
  • 11
0

Try this one with all special symbols

$.validator.addMethod("pwdcheck", function(value) {
    return /[A-Z]/.test(value) &&
           /\d/.test(value) && 
           /[=!\-@._*\$\#\%\^\&\(\)\~\`\<\>\/\?\\\|\{\}\[\]\;\:\'\"\,\+]/.test(value)
});
Chandni Soni
  • 377
  • 4
  • 16
0

The below method will check one capital letter, one numerical and one special character.

For length check you can add minlenth:8, maxlength:20

$.validator.addMethod("passwordFormatCheck", function(value, element) {
    return this.optional(element) || /^(?=.*\d)(?=.*[A-Z])(?=.*\W).*$/i.test(value);
}, 'Password must contain one capital letter,one numerical and one special character');
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26