Javascript regular expression password validation having special characters

212,913

Solution 1

Use positive lookahead assertions:

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.

  • (?=.*[0-9]) - Assert a string has at least one number;
  • (?=.*[!@#$%^&*]) - Assert a string has at least one special character.

Solution 2

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters"); 
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter.");
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit."); 
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version

Solution 3

I use the following script for min 8 letter password, with at least a symbol, upper and lower case letters and a number

function checkPassword(str)
{
    var re = /^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    return re.test(str);
}

Solution 4

you can make your own regular expression for javascript validation

    /^            : Start
    (?=.{8,})        : Length
    (?=.*[a-zA-Z])   : Letters
    (?=.*\d)         : Digits
    (?=.*[!#$%&? "]) : Special characters
    $/              : End



        (/^
        (?=.*\d)                //should contain at least one digit
        (?=.*[a-z])             //should contain at least one lower case
        (?=.*[A-Z])             //should contain at least one upper case
        [a-zA-Z0-9]{8,}         //should contain at least 8 from the mentioned characters

        $/)

Example:-   /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

Solution 5

Don't try and do too much in one step. Keep each rule separate.

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters");
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter."); 
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit.");
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}
Share:
212,913
Srikanth Sridhar
Author by

Srikanth Sridhar

Updated on July 05, 2022

Comments

  • Srikanth Sridhar
    Srikanth Sridhar almost 2 years

    I am trying to validate the password using regular expression. The password is getting updated if we have all the characters as alphabets. Where am i going wrong ? is the regular expression right ?

    function validatePassword() {
        var newPassword = document.getElementById('changePasswordForm').newPassword.value;
        var minNumberofChars = 6;
        var maxNumberofChars = 16;
        var regularExpression  = /^[a-zA-Z0-9!@#$%^&*]{6,16}$/;
        alert(newPassword); 
        if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars){
            return false;
        }
        if(!regularExpression.test(newPassword)) {
            alert("password should contain atleast one number and one special character");
            return false;
        }
    }
    
  • sQVe
    sQVe over 11 years
    Possible to shorten regex to /^(?=.*[\d])(?=.*[!@#$%^&*])[\w!@#$%^&*]{6,16}$/
  • Bhuvan
    Bhuvan about 11 years
    /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/.tes‌​t("12345678@12") will return true. What If I want to make it mandatory to include alphabets also?
  • saada
    saada over 10 years
    Add these if you want to restrict uppercase or lowercase: if (p.search(/[a-z]/) < 0) { errors.push("Your password must contain at least one lowercase letter.") } if (p.search(/[A-Z]/) < 0) { errors.push("Your password must contain at least one uppercase letter.") }
  • Saras Arya
    Saras Arya over 8 years
    This failed for XYZ@123
  • mumair
    mumair over 8 years
    @SarasArya add @ in special characters. it will start working. It not rocket science!
  • Scott Gartner
    Scott Gartner about 7 years
    Here is a more dynamic solution, but basically uses this same concept: jsfiddle.net/omnius/p6uxjntg
  • vahdet
    vahdet about 6 years
    Nice and precise. This way, it satisfies the default password policy of AWS Cognito User Pools.
  • VirtualProdigy
    VirtualProdigy over 5 years
    Does anyone know why this regex expression would not work if I var regexPttn = new RegExp("/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,1‌​6}$/"); For some reason using the creator breaks it.
  • Antonino
    Antonino almost 5 years
    @Bhuvan I used this answer to improve the expression provided. First of all including more special characters [space, hyphen, question mark, slash, backslash] and - above all - I increased the minimum number of characters because 6 characters passwords are highly insecure, especially if not flanked by login failures monitoring and/or 2FA. That said, I came to this: ^(?=.*[0-9])(?=.*[- ?!@#$%^&*\/\\])(?=.*[A-Z])(?=.*[a-z])[a-zA-Z0-9- ?!@#$%^&*\/\\]{8,30}$
  • Ivar
    Ivar almost 4 years
    I would change [a-zA-Z0-9!@#$%^&*]{6,16} to .{6,16} so that you can enter any character (as long as the password contains the number and special character). I don't see any reason to reject a password simply because it contains a + for instance.
  • Geethanga
    Geethanga over 3 years
    @VirtualProdigy you should use it like this var regularExpression = new RegExp('^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,20‌​}$'); notice that we had to remove the slashes in the start and the end.
  • prahack
    prahack about 3 years
    What about the '@' and '^' symbols?
  • Suwadith
    Suwadith about 3 years
    @prahack /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[a-zA-Z!#$@^%&? "])[a-zA-Z0-9!#$@^%&?]{8,20}$/
  • Marco Rehmer
    Marco Rehmer about 3 years
    Hi, welcome to stack overflow. Please provide a code sample for better understanding
  • Sanat Gupta
    Sanat Gupta almost 3 years
    An uppercase character should be required it's not working for uppercase charector
  • MechaCode
    MechaCode over 2 years
    It accepts spaces.
  • Sanat Gupta
    Sanat Gupta over 2 years
    @MechaCode you can use this regex I hope you will get your goal. ^((?!.*[\s])(?=.*[A-Z])(?=.*\d).{8,15})
  • Isuru Lakruwan
    Isuru Lakruwan about 2 years
    works well! Thank you
  • Javano Collins
    Javano Collins about 2 years
    Special character requirement not working