41

How would you create a regular expression for a value that should contain at least one number? The user can enter any special character, letter etc., but should contain at least one number.

I tried with pattern="[\w+]{6,20}" and

(?=.*\d)(*[a-z])(*[A-Z]).{6,20}

Neither are working.

senfo
  • 28,488
  • 15
  • 76
  • 106
Prashobh
  • 9,216
  • 15
  • 61
  • 91
  • Please, clarify: Any number or one from a range? The position of the number(s) inside the string. Why you marked that answer as correct? – Poniros Feb 14 '19 at 22:07

3 Answers3

61

Try using this pattern

.*[0-9].*

For 6 to 20 use this

^(?=.*\d).{6,20}$ 
code_rum
  • 872
  • 6
  • 21
  • Shouldn't it be like this? : .*[0-9]+.* He writes "At Least One Number". Although the whole question is disappointing ( check comment ). – Poniros Feb 14 '19 at 21:56
  • @Poniros the + is redundant. Any more digit can be matched with `.*` which is placed before and after the token [0-9]. – paul Jun 28 '19 at 09:24
0

You can use this pattern:

/^(?=.{6,20}$)\D*\d/
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

/?=\D*\d/

/? is to check whether it has \D*

\D* means the following characters have no digits

\d refers to must have ending digit

Alfred Huang
  • 156
  • 2
  • 4