-3

I am trying to implement maximum case in JavaScript for password validation.

I have a scenario where in password user should enter maximum 5 characters (a-z,A-Z) and password length having no restriction

  1. Passsword length no limit
  2. except (a-z,A-Z) ,there is no limtation
  3. charcter(a-z,A-Z) will have atmost 5 in password .Not more than that.Sequence doesnot matter.

I tried /[^A-Z,a-z]*(?:[A-Z,a-z][^A-Z,a-z]*){0,5}/

But it is not working. Kindly help

Thomas
  • 11,958
  • 1
  • 14
  • 23

4 Answers4

0

You can just count how many characters you have in the password like so:

if(password.match(/[a-zA-Z]/g).length > 5){ /* reject */ }
Bellian
  • 2,009
  • 14
  • 20
  • reject on > 5? Type mismatch? – iquellis Sep 05 '17 at 13:06
  • @iquellis no, that's exactly the requirement. `charcter(a-z,A-Z) will have atmost 5 in password. Not more than that.` – Thomas Sep 05 '17 at 13:16
  • Oops, yes, you are right. Was thinking of password policy or sth. like that. – iquellis Sep 05 '17 at 13:17
  • This is a regex flag. `g` is the global flag and allows you to find all matches instad of just one. (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) – Bellian Sep 06 '17 at 08:01
0

You can use the below regex for password validation.

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{5,20})

It validates :

  1. Must contain ! digit [0-9]
  2. One lowercase character [a-z]
  3. One uppercase character [A-Z]
  4. One symbol [@#$%]
  5. Length of password must be between [5-20].
  • I need a regex to test my "password" to contain max 5 alphabet(a-z,A-Z) in any sequence.user can input other things in any number and sequence .Can i get specific regex instead of in combination – Sudhanshu Agarwal Sep 05 '17 at 13:20
  • Can you tell some example how your password would look like?@SudhanshuAgarwal –  Sep 06 '17 at 06:21
0

Break it down and solve it step by step

Alphabet only - define your character set

/[A-Za-z]/

Maximum length of 5 - use a quantifier

/[A-Za-z]{0,5}/

Nothing else is allowed - wrap it with ^ and $

/^[A-Za-z]{0,5}$/
nvbach91
  • 166
  • 8
  • I need a regex to test my "password" to contain max 5 alphabet(a-z, A-Z) in any sequence.user can input other things in any number and sequence.Can i get specific regex for my requirement?This will only test string which are having max 5 characters, no other input.But in my case max 5 character with any number or sequence of other input – Sudhanshu Agarwal Sep 05 '17 at 13:23
  • Sorry mate, I didn't understand your question at first. Bellian's solution is the best one but you need to do one more check in case password.match(/[a-zA-Z]/g) returns null when it doesn't find any a-zA-Z character in the password – nvbach91 Sep 06 '17 at 18:12