Abhishek
Abhishek

Reputation: 49

Regex more than 4 characters containing all except blankspace and new line

I want a Regex for client side password Html5 validation, with no knowledge of how regex works; I found the best answer in this regex ((?=.*[^a-zA-Z])(?!\s).{4,}) but it needs necessary a number. My requirements are:

Any input more than 4 alpha-numerics or special characters except blank-space and new-line.

Please help!

Upvotes: 0

Views: 136

Answers (3)

Matthias Wimmer
Matthias Wimmer

Reputation: 4009

If you want to include the requirement of having at least one digit character you might use:

    ^([^\s]{4,}[0-9][^\s]*)|([^\s]{3,}[0-9][^\s]+)|([^\s]{2,}[0-9][^\s]{2,})|([^\s]+[0-9][^\s]{3,})|([^\s]*[0-9][^\s]{4,})$

(Requires at least 5 non-whitespace characters including at least one digit.)

Well, it's a bit verbouse to do this in regex, I know.

Upvotes: 0

Amit
Amit

Reputation: 46351

You can use this ^\S{5,}$. It means:

  1. Match beginning of input
  2. Match a non whitespace character ->

    2.1 As many as possible, but at least 5

  3. Match end of input

See snippet:

var passwords = [
  'aa',
  'abcde',
  'ab cd',
  'abcdefg',
  'a1234',
  'a1234 '
];

var rePassword = /^\S{5,}$/

for(var i = 0; i < passwords.length; i++) {
  console.log(passwords[i], rePassword.test(passwords[i]));
}

Upvotes: 1

w.b
w.b

Reputation: 11238

I would use something like ^(?=.*\d)\S{5,}$, where

(?=.*\d) is a positive lookahead asserting the password contains at least 1 digit

\S{5,} matches at least 5 non-whitespace characters.

Demo on regex101.com

Upvotes: 0

Related Questions