Home > Net >  Set minimum length restriction to Password Validation - Regular Expression
Set minimum length restriction to Password Validation - Regular Expression

Time:03-31

I have a regular expression for validating passwords.

/[\w\d]*(([0-9] .*[A-Za-z] .*)|[A-Za-z] .*([0-9] .*))/

This regex matches any words which contain letters and numbers in them.

I want to add a minimum length restriction as well, I got to know we can use {4,} to add a minimum length of 4.

But I am not able to figure out how to add this minimum length to the whole expression.

For example: The above regex matches p12 as valid.

I dont want it to match words with letters and numbers with a length of less than 4.

I tried this, but this did not work

/[\w\d]*(([0-9] .*[A-Za-z] .*)|[A-Za-z] .*([0-9] .*)){4,}/

Any help with respect to adding minimum length restriction to the whole expression would be appriciated.

Thank you.

CodePudding user response:

Using \w also matches \d so this parts [\w\d]* can be written as just \w*

If you want to match only word characters, you could use for example 2 assertions for the char a-z and a digit.

Using a case insensitive pattern:

/^(?=[^\d\n]*\d)(?=[^a-z\n]*[a-z])\w{4,}$/i

Regex demo

const regex = /^(?=[^\d\n]*\d)(?=[^a-z\n]*[a-z])\w{4,}$/;
[
  "p12",
  "1234",
  "abcs",
  "p123"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));

  • Related