开发者

Trouble with the simplest regex

开发者 https://www.devze.com 2023-01-14 13:10 出处:网络
I\'m trying to validate an ASP TextBox that can only have 1-2 digits (not zero) using the following regex:

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.

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." />  


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?!


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!


You can use this regex :

 ^([1-9]|[1-9][0-9])$
0

精彩评论

暂无评论...
验证码 换一张
取 消