表单验证检查非数字

时间:2013-11-15 01:28:32

标签: c# validation

在验证表单上的文本框时,我熟悉.Net中的验证控件,但不熟悉如何使用C#。我做了一些研究,我知道验证的基础知识,比如确保控件不为空。

但是你如何测试角色呢?我有一个只能是数字的文本框ID字段。我从研究中找到的任何东西都没有使用过这样的东西;它主要是IsNullOrEmpty

如何实现类似的功能来测试字符串字段中的数值?

if (string.IsNullOrEmpty(rTxtBoxFormatID.Text))
{
    ValidationMessages.Add("Missing Product Number");
}

我在下面解决了这个问题,我需要将它与if语句中的comobox.selectedindex进行比较。

if (string.IsNullOrEmpty(cmboBoxStock.SelectedIndex.ToString()))
{
     rLblStockIDError.Text = "Missing Stock Number";
}

3 个答案:

答案 0 :(得分:2)

您可以使用Int32.TryParseDouble.TryParse来检查字符串是否为数字。

使用Int32.TryParse

int number;
string value = "123";
bool result = Int32.TryParse(value, out number);

使用Double.TryParse

double number;
string value = "123.123";
bool result = Double.TryParse(value, out number)

您的代码将是

int number;
if (!Int32.TryParse(rTxtBoxFormatID.Text, out number))
{
    ValidationMessages.Add("Missing Product Number");

答案 1 :(得分:0)

您可以使用正则表达式检查字符串中的任何非数字字符。

Regex r = new Regex(@"\D");
if (!r.IsMatch(rTxtBoxFormatID.Text))
{
    // The text contains only numeric characters
}

\ D匹配十进制数字以外的任何字符。 有关Regular Expression的更多信息。

答案 2 :(得分:0)

而不是在c#代码中执行它,你可以在aspx上使用RegularExpressionValidator,RequiredFieldValidator,regex

<asp:TextBox ID="txtNo" runat="server"/>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
<asp:RegularExpressionValidator ID="regexpName" runat="server" ErrorMessage="Product Number can only be numeric" ControlToValidate="txtNo" ValidationExpression="^[0-9]$" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtNo" errormessage="Missing Product Number" />

http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp

http://msdn.microsoft.com/en-us/library/ff650303.aspx

http://www.dotnetperls.com/regex-match