2

I'm trying to write a regex for javascript which will allow letters and numbers but won't allow numbers alone.

So '12 Test Street' would validate, as would 'test street' but not '12'.

Not that familiar with regexs so I've no idea where to start. I managed to write:

^([A-Za-z\d\s]+[A-Za-z\s])+$

That does work to a point but if a space is then added to the end of the numbers, it will validate again.

Alex Foxleigh
  • 1,784
  • 2
  • 21
  • 47

2 Answers2

8

You can solve this easily with a negative look-ahead:

^(?!\d+$)[a-zA-Z\d\s]+$

Note that this allows space-only strings. I'll leave it as a small exercise to change the expression if that's not desired. :)

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • This comes very close, however like my example above it will allow you to enter just numbers if it's followed by a space. A single trailing space is fine as I can just .trim() but if you entered a value of "123 243534534" it will pass validation. – Alex Foxleigh Jul 02 '14 at 16:07
  • 2
    Change the look-ahead to `(?![\d\s]+$)`. – Tomalak Jul 02 '14 at 16:08
  • 1
    Also see: http://stackoverflow.com/questions/3802192/regexp-java-for-password-validation - It's the same approach. – Tomalak Jul 02 '14 at 16:20
1

If I interpret almost strictly (you did not mention whitespace characters) your question I suppose this will work:

^\d*[a-zA-Z][a-zA-Z\d\s]*$
dgiugg
  • 1,294
  • 14
  • 23