Sharique
Sharique

Reputation: 859

Regex configuration in javascript

This is what I have so far,

^(?=.'{'8,14'}'$)(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9!@#$%^&*]).*$ 

which allows one atleast one lowercase , one uppercase, one number and on special character with minimun length 8 and max length 14.

And if i don't want any number then I am using this

^(?=.'{'8,14'}')(?=.*^([^0-9]*)$)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9!@#$%^&*]).*$

But if I want that it should not accept any lowercase then what it should look like? And if later on I want to accept lowercase and not uppercase then how it should be or if I want to remove special character then how the expression will look like. I don't have any idea on javascript and regex thing so please help me with the expression and I am not allowed to do it using iteration.

Note: '{'8,14'}' here single quote is just used as escape sequence so please don't bother about that

Upvotes: 2

Views: 62

Answers (2)

vks
vks

Reputation: 67968

But if I want that it should not accept any lowercase then what it should look like?

Then you can add negative lookahead .

(?!.*[a-z])

And if later on I want to accept lowercase and not uppercase then how it should be

(?!.*[A-Z])

minimun length 8 and max length 14.

For this you dont need lookahead.Just change .*$ to .{8,14}$.

Upvotes: 1

James
James

Reputation: 111910

It may be clearer/easier to split up your logic into multiple regexes and run the string through each of them:

var rules = [
  /^.{8,14}$/,
  /[a-z]/,
  /[A-Z]/,
  /[0-9]/,
  /[!@#$%^&]/
];

function isValid(str) {
  for (var i = 0, l = rules.length; i < l; i++)
    if (!rules[i].test(str)) return false;
  return true;
}

isValid('abc'); // false
isValid('a0%Aeeee'); // true

You can also add a final /^[a-zA-Z0-9!@#$%^&]+$/ to ensure that only the characters you specify have been used at all.

Upvotes: 1

Related Questions