0

My web application contains a text box for which I would like to restrict its input. I would like to prevent the user from entering text that:

  • Starts with white space
  • Starts with something other than a digit
  • Contains alphanumeric characters after the leading character.

Thank you for your suggestions!

Steve Guidi
  • 19,700
  • 9
  • 74
  • 90
Surya sasidhar
  • 29,607
  • 57
  • 139
  • 219

2 Answers2

3

For ASCII characters you could use:

^[a-zA-Z][a-zA-Z0-9]*$ // Note you don't need the "+" after the first character group.
                       // or...
(?i:^[a-z][a-z0-9]*$)  // Slightly shorter, albeit more unreadable, syntax (?i: ... ) makes the expression case-insensitive 

If you want to match empty string just wrap the expression in "( ... )?", like so:

^([a-zA-Z][a-zA-Z0-9]*)?$

If you want to work in Unicode you might want to use:

^\p{L}[\p{L}\p{Nd}]*$

Unicode w. empty string:

^(\p{L}[\p{L}\p{Nd}]*)?$

To read more about unicode possibilities in regex, see this page on Regular-Expressions.info.

Edit

Just collected all possibilities in one answer.

JohannesH
  • 6,430
  • 5
  • 37
  • 71
3

Not to start with white space of alpha numeric: [a-zA-Z]+
Followed by 0 or more alphanumeric: [a-zA-Z0-9]*

Final expression

^[a-zA-Z]+[a-zA-Z0-9]*$
Ramesh Soni
  • 15,867
  • 28
  • 93
  • 113