Jabir Jabir - 6 months ago 16
HTML Question

What is the validation expression (syntax) for the following type of input (in ASP.NET)?

I want to validate user input in a textbox while using visual studio to write code. In a text box, user have to input the street name, a space and then the number (e.g. road 65)

The requirements are:


  • street name shall start with letters

  • then it should be a space

  • then it should be a number



What is the validation Expression for this?

I am using regular validation expression in visual studio.

<asp:RegularExpressionValidator ID="RegularExpressionValidatorStreet" runat="server"
ErrorMessage="This is wrong!" ValidationExpression="^[a-zA-Z\s][0-9]$"
ControlToValidate="streettxt"></asp:RegularExpressionValidator><br />

AGB AGB
Answer

Your expression is only matching one character in [a-zA-Z\s] followed by one character in [0-9], so it would match "r6" or " 6" or "Z8" but not "road 65".


Since you want to match at least one or more letters, followed by one whitespace character, and finally one or more digits, try:

ValidationExpression="^[a-zA-Z]+\s[0-9]+$"

Explanation:

  • Will match: "road 65", "qWerTy 6", or "q 23983049823948"
  • Will not match: "road 65", " road 65", nor "road65"
  • ^ asserts position at start of the string
  • [a-zA-Z]+ match a single character between a-z or A-Z between one and unlimited times, as many times as possible
  • \s match any single white space character
  • [0-9]+ match a single character between 0-9 between one and unlimited times, as many times as possible
  • $ assert position at end of the string

Notes:

If you want to match when there is between one and unlimited whitespace characters, add the quantifier onto \s+:

ValidationExpression="^[a-zA-Z]+\s+[0-9]+$"

which will match both "road 65" and "road 65" but not "road65".