How do I ensure a text box is alphanumeric but without a leading digit?

后端 未结 2 1428
渐次进展
渐次进展 2021-01-28 11:42

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 s
2条回答
  •  爱一瞬间的悲伤
    2021-01-28 12:28

    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.

提交回复
热议问题