laurenmc34
laurenmc34

Reputation: 13

Regular Expression in Javascript for password validation

I am trying to create a regular expression that validates a user's password when they create it. The password needs to be:

  1. at least 6 characters long and can be any type of character
  2. each character that is used needs to appear in the password exactly 3 times.

Good examples:

AAABBB
ABABBA
+++===
+ar++arra
myyymm
/Arrr/AA/

Does anyone know which regex would accomplish this?

Upvotes: 1

Views: 389

Answers (3)

SamWhan
SamWhan

Reputation: 8332

An alternative solution since you're allowing code (which your question imply you wouldn't ;)

Using a function like verifyPass below should do the trick. It gradually replaces any valid three letter combination with an empty string. Checking that this is done in more than one iteration (it's at least 6 characters) and ending up with an empty string in the end, means it's a valid password.

function verifyPass(pass) {
  var re = /^(.)((?:(?!\1).)*)\1((?:(?!\1).)*)\1((?:(?!\1).)*)$/,
      cnt=0;

  while(re.test(pass)) {
    pass = pass.replace(re, '$2$3$4');
    cnt++;
  }
  return pass==='' && cnt>1;
}

var testItems = [
      '123123123',
      'AAABBB',
      'AAABBBAAA',
      'Qwerty',
      'ABABBA',
      '+++===',
      '111',
      'qweqwd',
      'sdcjhsdfkj',
      '+ar++arra',
      'mYYYmms',
      '/Arrr/AA/'
  ];
  
  testItems.forEach(function(item) {
    document.write('<span style="color:' + (verifyPass(item) ? 'green' : 'red') + ';">' + item + '</span> <br/>');
  });

Upvotes: 0

Rjoydip
Rjoydip

Reputation: 66

For 1st option you have to check without regex.

var str = "your password";
var pattern = /(.)(.*\1){3}/;
if(str.length >= 6){
   // It will give you boolean as return
   // If it is match then it return true else false
   pattern.test(str);
}

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You can ease yourself by sorting the password before testing it:

$('button').on('click', function(){
var s = $('#password').val();
var split = s.split("").sort().join("");
if(/^(?:(.)\1{2}(?!\1)){2,}$/.test(split))
   console.log("Valid password");
else
   console.log("Invalid password");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="password">
<button>Test me</button>

Upvotes: 2

Related Questions