81

I have a regex

/^([a-zA-Z0-9]+)$/

this just allows only alphanumerics but also if I insert only number(s) or only character(s) then also it accepts it. I want it to work like the field should accept only alphanumeric values but the value must contain at least both 1 character and 1 number.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
OM The Eternity
  • 15,694
  • 44
  • 120
  • 182

10 Answers10

137

Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 7
    This is better than the below solution: If you wanted to add a hyphen and underscore check, this will still work all around. Ex: `^(?=.*[0-9])(?=.*[a-z])([a-z0-9_-]+)$` abc-d12345 – Sababado May 03 '12 at 16:29
  • This gives a good explanation on how lookaround works: http://www.regular-expressions.info/lookaround.html – jamesmortensen Jul 22 '16 at 06:29
  • What to do if we want to specify length of string as well e.g.11 ? – Zaveed Abbasi Jun 13 '17 at 15:11
  • @Zaveed Abbasi That sounds like a great question. Go ahead and [ask it](https://stackoverflow.com/questions/ask)! Make sure that your question is very precise on what you want, i.e. do you want the overall length to be 11? It's best to also mention a couple of testcases and whether you want them to much. Testcases such as `1234567890a1`, `1abcdefghijklmo`, `1234567890a`. – phihag Jun 13 '17 at 15:19
  • Yes exactly, i am in need of a regex that just validates the string with length exactly 11 and that has at-least on character and one digit – Zaveed Abbasi Jun 13 '17 at 16:07
  • 1
    Dear @phihag , as you said asked it at https://stackoverflow.com/questions/44528450/regex-for-alphanumeric-string-with-at-least-1-number-and-1-character-and-a-fixed – Zaveed Abbasi Jun 13 '17 at 17:58
  • 7
    WARNING: this regex will fail on strings that contain special characters. It matches only strings that have letters and numbers. It does not strings that contains letters, numbers, and special chars. – Judah Gabriel Himango Mar 21 '18 at 21:49
  • @JudahHimango `^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$` I found this one. It will helps. – Pratik Butani Dec 14 '18 at 10:36
  • @JudahGabrielHimango You can replace the special characters first or during the check using `/[!@#$%^&*]/` – Jan Ndungu May 09 '21 at 09:45
  • What does this do (?=.*[0-9]) (why the "." sign) I don't understand. – matt.aurelio Jul 14 '22 at 22:54
  • @matt.aurelio `.` matches everything. `(?=.*[0-9])` means: _Only match (the stuff after this expression) if after skipping 0-x characters you encounter a digit_, or in other words: _fail to match if even after skipping any amount of characters you don't find a digit_. – phihag Jul 14 '22 at 23:51
24

This RE will do:

/^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i

Explanation of RE:

  • Match either of the following:
    1. At least one number, then one letter or
    2. At least one letter, then one number plus
  • Any remaining numbers and letters

  • (?:...) creates an unreferenced group
  • /i is the ignore-case flag, so that a-z == a-zA-Z.
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Why do we need case sensitivity in this? – OM The Eternity Oct 07 '11 at 08:40
  • The /i at the end makes it case-insensitive. – Kasaku Oct 07 '11 at 08:42
  • In your code, you mentioned `a-zA-Z`. I've done some test yesterday, and deduced that the `/[a-z]/i` is slightly faster than `/[a-zA-Z]/`. See: http://jsperf.com/regexp-a-z-i-vs-a-za-z – Rob W Oct 07 '11 at 08:43
  • 3
    @RobW The data shown on the linked page clashes with your statement. On Chrome, `/[a-zA-Z]/` seems to be faster. But that's kind of a silly test anyway, and performance doesn't really matter in the first place. – phihag Oct 10 '11 at 06:59
  • If you wanted to add a check for hyphens and underscores to this, your regex will break with any hyphen or underscore before the letter/number pair. Ex: `^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9_-]*$`abc-d12345 – Sababado May 03 '12 at 16:27
  • This is the best solution, since it only requires searching through the string one time. Multiple lookaheads and multiple regular expressions, as suggested in other answers, require stepping through each character of the string multiple times. – Nathan K May 19 '16 at 18:46
22

I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand.

An easier solution would be to retain your existing regex, then create two new regexes to test for your "at least one alphabetic" and "at least one numeric".

So, test for this :-

/^([a-zA-Z0-9]+)$/

Then this :-

/\d/

Then this :-

/[A-Z]/i

If your string passes all three regexes, you have the answer you need.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Paul Alan Taylor
  • 10,474
  • 1
  • 26
  • 42
  • I really like the simplicity of this. Much, much easier to read and maintain. – Josh Harrison Apr 20 '16 at 16:56
  • Hello Paul.. I am looking for a regex with only numbers[0-9] and two spacial characters [.,] and then ' ml' - at least one number should be there.. Your solution looks great but I am not able to write the exact regex.. I tried this : .match(/(?=.*\d)[0-9][,.]{1,5} ml/g) . its not working. Can you help me out. – Sanket Tarodekar Jul 11 '18 at 08:26
  • BEAUTIFUL and GENIUS. This should be the accepted answer. – Ilker Cat Sep 15 '20 at 08:30
14

The accepted answers is not worked as it is not allow to enter special characters.

Its worked perfect for me.

^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$

  • one digit must
  • one character must (lower or upper)
  • every other things optional

Thank you.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • From the question: `the field should accept only alphanumeric values` – Toto Dec 14 '18 at 10:46
  • **Regex pattern to match at least 1 number and 1 character in a string** means at least alphanumeric MUST but every other thing is fine it you enter or not. – Pratik Butani Dec 14 '18 at 11:20
  • Reread the question. Second line: `the field should accept only alphanumeric values` – Toto Dec 14 '18 at 11:23
  • Reread first line : `if I insert only number(s) or only character(s) then also it accepts` but he want both must. So I think my answer is not wrong. – Pratik Butani Dec 14 '18 at 11:43
  • They say their actual regex accepts only number or only alpha but they want at least 1 digit and 1 alpha **AND** only alphanumeric. The accepted answer was given 7 seven years ago and it seems to answer perfectly. But you're allowed to imagine what you want. Have a good day. – Toto Dec 14 '18 at 12:22
10

While the accepted answer is correct, I find this regex a lot easier to read:

REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"
Neuron
  • 5,141
  • 5
  • 38
  • 59
7

This solution accepts at least 1 number and at least 1 character:

[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
Neuron
  • 5,141
  • 5
  • 38
  • 59
user2043372
  • 69
  • 1
  • 2
4

And an idea with a negative check.

/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
  • ^(?! at start look ahead if string does not
  • \d*$ contain only digits | or
  • [a-z]*$ contain only letters
  • [a-z\d]+$ matches one or more letters or digits until $ end.

Have a look at this regex101 demo

(the i flag turns on caseless matching: a-z matches a-zA-Z)

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
3

Maybe a bit late, but this is my RE:

/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/

Explanation:

\w* -> 0 or more alphanumeric digits, at the beginning

\d+[a-zA-Z]|[a-zA-Z]+\d -> a digit + a letter OR a letter + a digit

\w* -> 0 or more alphanumeric digits, again

I hope it was understandable

Pablo Garcia
  • 138
  • 10
1

What about simply:

/[0-9][a-zA-Z]|[a-zA-Z][0-9]/

Worked like a charm for me...

Edit following comments:

Well, some shortsighting of my own late at night: apologies for the inconvenience...

The - incomplete - underlying idea was that only one "transition" from a digit to an alpha or from an alpha to a digit was needed somewhere to answer the question.

But next regex should do the job for a string only comprised of alphanumeric characters:

/^[0-9a-zA-Z]*([0-9][a-zA-Z]|[a-zA-Z][0-9])[0-9a-zA-Z]*$/

which in Javascript can be furthermore simplified as:

/^[0-9a-z]*([0-9][a-z]|[a-z][0-9])[0-9a-z]*$/i

In IMHO it's more straigthforward to read and understand than some other answers (no backtraking and the like).

Hope this helps.

NemoNobody
  • 11
  • 2
  • 3
  • I miss a `^` at the beginning and a `$` at the end! You have to ensure that there are only alphnumerics. But then this doesn't work. – Andy A. Dec 06 '22 at 00:04
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 06 '22 at 00:07
-1

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)
will
  • 153
  • 3
  • 6