4

The language is javascript.

Strings that would pass:

JavaScript1*

Pu54 325

()9c

Strings that would not pass:

654fff

%^(dFE

I tried the following:

var matches = password.match(/\d+/g);
if(matches != null)
 {
        //password contains a number
        //check to see if string contains a letter
        if(password.match(/[a-z]/i))
        {
            //string contains a letter and a number
        }
 }
Michael Drum
  • 1,151
  • 5
  • 14
  • 26

1 Answers1

5

You can use Regex:

I took it from here: Regex for Password

var checkPassword = function(password){
    return !!password.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%* #+=\(\)\^?&])[A-Za-z\d$@$!%* #+=\(\)\^?&]{3,}$/);
};

I use this Regex:

Minimum 3 characters at least 1 Alphabet, 1 Number and 1 Special Character:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%* #=+\(\)\^?&])[A-Za-z\d$@$!%* #=+\(\)\^?&]{3,}$"

This regex will enforce these rules:

At least one English letter, (?=.*?[A-Za-z])

At least one digit, (?=.*\d)

At least one special character, (?=.[$@$!% #+=()\^?&]) Add more if you like...

Minimum length of 3 characters (?=.[$@$!% #?&])[A-Za-z\d$@$!%* #+=()\^?&]{3,} include spaces

If you want to add more special characters, you can add it to the Regex like I have added '(' (you need to add it in two places).

And for those of you who ask yourself what are those two exclamation points, here is the answer: What is the !! (not not) operator in JavaScript?

Community
  • 1
  • 1
sidanmor
  • 5,079
  • 3
  • 23
  • 31
  • That's perfect. Thank you! – Michael Drum Nov 30 '16 at 07:12
  • @michael-drum The 2 exclamation points are for the function to always return boolean - look at this http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – sidanmor Nov 30 '16 at 07:24
  • @michael-drum So why didn't you mark this answer as the "Answer to your question"? – sidanmor Nov 30 '16 at 08:13
  • So far, I am aware that it doesn't work with spaces or "+"s. A string with those characters should return true; – Michael Drum Nov 30 '16 at 08:24
  • @michael-drum you should add them to the Special Characters list - like this /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%* #+=?&])[A-Za-z\d$@$!%* #+=?&]{3,}$/ – sidanmor Nov 30 '16 at 08:48
  • @michael-drum check it now, after my last update. I have added space and +, =, ( and ) to the Regexp - if you need more special characters add them to the Regexp like I did. – sidanmor Nov 30 '16 at 08:53
  • It works fine for me. Please give me some examples that don't work for you – sidanmor Nov 30 '16 at 10:19