-1

I'm trying to write a regex to validate below conditions in a password string

  • Atleast one number and a letter
  • Should not contain any special characters

Tried this regex

[a-zA-Z]+[0-9]+[a-zA-Z0-9]*|[0-9]+[a-zA-Z][a-zA-Z0-9]*

But it allows special characters. Any help would be appreciated!

Example

  • aaaa - Not accepted
  • 11111 - Not accepted
  • aaaa1 - Accepted
  • aaaa1* - Not accepted
Chris
  • 1,271
  • 2
  • 15
  • 35

3 Answers3

3

Try this Regex:

(?=.*\d.*)(?=.*[a-zA-Z].*)[0-9A-Za-z]+

The first two sections will promise you one number and one a-z characters and the third section allows you to insert numbers or a-z characters.

4EACH
  • 1,540
  • 3
  • 14
  • 24
  • I think this will have the same problems as OPs expression regarding special characters!? If not why not? – kutschkem Apr 12 '18 at 15:16
  • You don't need additional `.*` in your lookaheads, additional computation for literally nothing. Instead, shorten (and improve performance) by using `(?=\D*\d)(?=[^a-zA-Z]*[a-zA-Z])[0-9A-Za-z]+` – ctwheels Apr 12 '18 at 16:12
0

You could make a regex that check first the first character, if it is a letter ^[a-zA-Z], then expect an unknown number of alphanum char [a-zA-Z0-9]*. Then expect at least one number [0-9]+ and finally expect another unknow number of of alphanum until the end [a-zA-Z0-9]*$. This look like :

^[a-zA-Z][a-zA-Z0-9]*[0-9]+[a-zA-Z0-9]*$

Make the equivalent if it starts with a number ^[0-9], then expect an unknown number of alphanum char [a-zA-Z0-9]*. Then expect at least one letter [a-zA-Z]+ and finally expect another unknow number of of alphanum until the end [a-zA-Z0-9]*$. This look like :

^[0-9][a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$

And make a OR betwenn this two regex :

^( [a-zA-Z][a-zA-Z0-9]*[0-9]+[a-zA-Z0-9]* | [0-9][a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*) $
vincrichaud
  • 1,998
  • 13
  • 26
-1

Your pattern should start with ^ (beginning of string) and end with $ (end of string). I assume your check succeeds if it finds an occurence of the pattern.

So it should be

^([a-zA-Z]+[0-9]+[a-zA-Z0-9]*|[0-9]+[a-zA-Z][a-zA-Z0-9]*)$
kutschkem
  • 6,194
  • 3
  • 16
  • 43
  • No, this is wrong `^[a-zA-Z]+[0-9]+[a-zA-Z0-9]*|[0-9]+[a-zA-Z][a-zA-Z0-9]*$`. You should be more specific. – ctwheels Apr 12 '18 at 14:57
  • @ctwheels Ok I edited to make it unmistakable what I meant. Before, you are right, it was a little ambiguous. And, as you correctly observed, just prepending ^ and appending $ is wrong because of the disjunction. – kutschkem Apr 12 '18 at 15:00