tags:

views:

50

answers:

3

I'm trying to validate an ASP TextBox that can only have 1-2 digits (not zero) using the following regex:

^[1-9]{1,2}

This regex doesn't validate if the field is empty (assumed it would due to the 1-2 part)

Also tried ^[1-9+]{1,2} to no avail.

I'm clearly a newbie to regex so your help is appreciated.

These are my controls:

<asp:TextBox ID="txtInHour" 
             MaxLength="2" 
             runat="server" 
             Text='<%# Bind("InHour") %>' 
            Width="80"/>


<asp:RegularExpressionValidator ID="rvInHour" 
                ControlToValidate="txtInHour" 
                Display="None" 
                ValidationExpression="^[1-9]{0,2}$" 
                runat="server" 
                ErrorMessage="InHour is incorrectly formatted." />  
+1  A: 

Hi there. The first thing I notice is that you don't allow zeros in your pattern. So 10 or 20 is not valid? The second thing is that you start with "starts with" AKA "^" but there's no "ends with" AKA "$"

So.. try this:

^[1-9][0-9]?$

In human readable:

  • starts with 1-9, followed by an optional digit from 0-9, end of string.

On the other hand I don't know what you've meant with ("no zeros") - no zeros at all?!

Jan.
Hey there, thanks for answering. I tried your solution but using this regex I can still leave the field empty and it's not getting validated
Eton B.
Well.. I have no clue about ASP.. But that PCRE-pattern is correct! Check your code logic!
Jan.
I updated my question with my controls' markup. I don't quite see why your solution is not working, makes perfect sense to me.
Eton B.
It's indeed a problem with RegularExpressionValidator. I've added an answer that explains.
Eton B.
Ah.. I see. Thanks for the update! That way nobody misses the part. Regards, jan.
Jan.
A: 

You can use this regex :

 ^([1-9]|[1-9][0-9])$
HoLyVieR
+1  A: 

I found out that for some reason RegularExpressionValidators don't work when there's no input to match against (blank fields) so I had to use a seperate RequiredFieldValidator. Thanks for your input everyone!

Eton B.