Number validation in required field validator

2020-05-25 07:11发布

Is it possible to put Number validation in required field validator in asp.net text box?

7条回答
做个烂人
2楼-- · 2020-05-25 07:32

You should use the CompareValidator, for example:

<asp:TextBox ID="txt" runat="server />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txt" Type="Integer"
   Operator="DataTypeCheck" ErrorMessage="Value must be an integer!" />

This is the most natural choice if you want a simple data type check. Otherwise if you want to verify a range use the RangeValidator suggestions. If you need a certain pattern use the RegularExpressionValidator.

Note that you'll want to add a RequiredFieldValidator as well since some validators will allow blank entries.

查看更多
女痞
3楼-- · 2020-05-25 07:33

A RequiredFieldValidator only checks if the field is filled in. It doesn't care what with.

You will need an extra CompareValidator with it's Operator set to DataTypeCheck and it's Type set to Integer. Note you need both: the CompareValidator will ignore an empty input.

查看更多
一夜七次
4楼-- · 2020-05-25 07:33

Yes, like this:

<asp:TextBox ID="tb" runat="server"></asp:TextBox>
<asp:RangeValidator ControlToValidate="tb" Type="Integer"></asp:RangeValidator>
查看更多
相关推荐>>
5楼-- · 2020-05-25 07:44

No, a RequiredFieldValidator can only verify that the field contains something.

If you want to verify that the field only contains digits, you can use a RegularExpressionValidator with the pattern "\d+".

查看更多
劳资没心,怎么记你
6楼-- · 2020-05-25 07:45

Another possibility is using the RegexpValidator and adding a regular expression that makes sure there's 1 or more digits in it, something like:

RegularExpressionValidator regexpvalidator = new RegularExpressionValidator(); 
regexpvalidator.ID = "RegularExpressionValidator1"; 
regexpvalidator.ValidationExpression = "\d+"; 
regexpvalidator.ControlToValidate = "YourControl"; 
regexpvalidator.ErrorMessage = "Please specify a digit"; 
regexpvalidator.SetFocusOnError = true; 
查看更多
ら.Afraid
7楼-- · 2020-05-25 07:49

Maybe you can use a RangeValidator attached to that textbox, setting Type to Integer or wathever.

RangeValidator class on MSDN

查看更多
登录 后发表回答