1

I've read other answers to other questions about RegularExpressionValidator but they haven't helped. I'm working on an ASP.NET C# app and I have a text field that needs to be a 1 or 2 digit number. Here's the control:

<asp:TextBox 
    ID="Hunt_Daily_Sitting_hrs" 
    runat="server" 
    class="form-control" 
    placeholder="hours" 
    type="number"></asp:TextBox>

As written, even though it specifies type="number", it allows mathematical operators. So people have been entering "6-8" as in "6 to 8 hours". On this page, the regular expression ^\d{1,2}$ flags such an entry. However, in my app, the line

<asp:RegularExpressionValidator 
    ID="HuntSitRegexp" 
    Display="Dynamic" 
    ControlToValidate="Hunt_Daily_Sitting_hrs" 
    ValidationExpression="^\d{1,2}$" 
    runat="server" 
    ErrorMessage="Please enter a number from 1-24" 
    Font-Size="Large" 
    ForeColor="Red" />

does not. A 3-digit number is immediately flagged, but an entry such as "6-8" is NOT immediately flagged. However, an entry such as "6-8" DOES fail submission in that the "Submit" button does nothing, indicating that Javascript validation has failed. So the user is left thinking, "What's wrong with the form? It won't submit but there is no error message."

juharr
  • 31,741
  • 4
  • 58
  • 93

3 Answers3

1

The ValidationExpression="^\d{1,2}$" is fine, but the regex checking is not enabled for an input of number type.

So, you need to change the asp:TextBox control type="number" to type="text".

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Try this Reg Ex instead

^[0-9]{1,2}$
Rex
  • 521
  • 3
  • 8
0

I think the answer with changing the type is correct one. However, I noticed that your ValidationExpression="^\d{1,2}$"
and ErrorMessage="Please enter a number from 1-24" do not match. It will take any 1-2 digit number.

The RegEx expression which will match only numbers 1-24 is following: ^(\d)$|^(1\d)$|^(2[0-4])$

tgralex
  • 794
  • 4
  • 14