Search code examples
javascriptjqueryregexpasswords

Javascript Password should not contain user's account name or parts of the user's full name that exceed two consecutive characters


I need to implement client side Password validation such that password should not contain user's account name or parts of the user's full name that exceed two consecutive characters.

I'm exposing the user name and full name on the client side. But so far I couldn't figure out the regex or any other approach to implement on the client side.

Example

username: test20@xyz.com
password: Usertest123 --> this should fail the validation since it contains "test" in both password and username.

Solution

  • I can only think of this:

    var name = "test20@xyz", password = "usertest123"
    
    var partsOfThreeLetters = name.match(/.{3}/g).concat(
                               name.substr(1).match(/.{3}/g),
                               name.substr(2).match(/.{3}/g) );
    new RegExp(partsOfThreeLetters.join("|"), "i").test(password); // true
    

    but I don't think regex is the appropriate tool here, since it would need escaping etc. You'd better use a simple substr/indexOf algorithm (see JavaScript case insensitive string comparison, How to check whether a string contains a substring in JavaScript?).