asp.net验证,以确保文本框具有整数值

mrb*_*lah 53 asp.net validation

我在文本框上有一个必需的验证设置,但我还必须确保它是一个整数.

我怎样才能做到这一点?

bdu*_*kes 116

如果你关注的只是该字段包含一个整数(即,不涉及范围),那么添加a CompareValidatorOperator属性设置为DataTypeCheck:

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />
Run Code Online (Sandbox Code Playgroud)

如果有一个特定范围的值有效(可能有),那么你可以使用a RangeValidator,如下所示:

<asp:RangeValidator runat="server" Type="Integer" 
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox" 
ErrorMessage="Value must be a whole number between 0 and 400" />
Run Code Online (Sandbox Code Playgroud)

这些只会验证TextBox中是否有文本,因此您也需要保留它RequiredFieldValidator.

正如@Mahin所说,请确保检查Page.IsValid服务器端的属性,否则验证程序仅适用于启用了JavaScript的用户.


Shi*_*mae 8

这对我很好:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
     ControlToValidate="YourTextBoxID"
     ErrorMessage="Only numeric allowed." ForeColor="Red"
     ValidationExpression="^[0-9]*$" ValidationGroup="NumericValidate">*
</asp:RegularExpressionValidator>
Run Code Online (Sandbox Code Playgroud)

我认为你也应该添加ValidationGroup="NumericValidate"到提交按钮.


Bra*_*don 5

使用Int32.TryParse。

 int integer;
 Int32.TryParse(Textbox.Text, out integer)
Run Code Online (Sandbox Code Playgroud)

它将返回一个 bool 以便您可以查看它们是否输入了有效的整数。