仅为数字输入验证文本框字段。

时间:2012-05-01 17:29:26

标签: c# validation textbox

我创建了一个基于表单的程序,需要一些输入验证。我需要确保用户只能在距离文本框中输入数值。

到目前为止,我已经检查过Textbox中有内容,但是如果它有值,那么它应该继续验证输入的值是否为数字:

else if (txtEvDistance.Text.Length == 0)
        {
            MessageBox.Show("Please enter the distance");
        }
else if (cboAddEvent.Text //is numeric)
        {
            MessageBox.Show("Please enter a valid numeric distance");
        }

12 个答案:

答案 0 :(得分:17)

您可以尝试使用TryParse方法,该方法允许您将字符串解析为整数并返回指示操作成功或失败的布尔结果。

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}

答案 1 :(得分:6)

如果您想要阻止用户在输入TextBox中的信息时输入非数字值,您可以像这样使用Event OnKeyPress:

private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
            if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
            if (e.KeyChar == (char)13) btnSearch_Click(sender, e);  //Allow Enter            
        }

如果用户使用鼠标粘贴TextBox中的信息(右键单击/粘贴),则此解决方案不起作用,在这种情况下,您应该添加额外的验证。

答案 2 :(得分:5)

这是另一个简单的解决方案

try
{
    int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}

答案 3 :(得分:4)

您可以在客户端使用 javascript 或在文本框中使用某些正则验证程序来执行此操作。

的Javascript

script type="text/javascript" language="javascript">
    function validateNumbersOnly(e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
            return true;
        }
        else {

            window.alert("This field accepts only Numbers");
            return false;
        }
    }
</script>

文本框(具有固定的ValidationExpression)

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator> 

答案 4 :(得分:2)

你可以这样做

   int outParse;

   // Check if the point entered is numeric or not
   if (Int32.TryParse(txtEvDistance.Text, out outParse) && outParse)
    {
       // Do what you want to do if numeric
    }
   else
    {
       // Do what you want to do if not numeric
    }     

答案 5 :(得分:2)

我同意Int.TryParse,但作为替代方案,您可以使用Regex。

 Regex nonNumericRegex = new Regex(@"\D");
 if (nonNumericRegex.IsMatch(txtEvDistance.Text))
 {
   //Contains non numeric characters.
   return false;
 }

答案 6 :(得分:1)

我有这个扩展,这是一种多用途:

    public static bool IsNumeric(this object value)
    {
        if (value == null || value is DateTime)
        {
            return false;
        }

        if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
        {
            return true;
        }

        try
        {
            if (value is string)
                Double.Parse(value as string);
            else
                Double.Parse(value.ToString());
            return true;
        }
        catch { }
        return false;
    }

适用于其他数据类型。应该适合你想做的事情。

答案 7 :(得分:1)

        if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
        {
            lblMessage.Text = string.Empty;
            lblMessage.Visible = true;
            lblMessage.ForeColor = Color.Maroon;
            lblMessage.Text = "You have not entered a number";
            return;
        }

答案 8 :(得分:1)

这是一个解决方案,允许数字只有减号或小数有减号和小数点。以前的大部分答案没有考虑选定的文字。如果将文本框的ShortcutsEnabled更改为false,则无法将垃圾粘贴到文本框中(它会禁用右键单击)。有些解决方案允许您在减号之前输入数据。请确认我已经抓住了所有东西!

        private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
        {
            if (numeric)
            {
                // Test first character - either text is blank or the selection starts at first character.
                if (txt.Text == "" || txt.SelectionStart == 0)
                {
                    // If the first character is a minus or digit, AND
                    // if the text does not contain a minus OR the selected text DOES contain a minus.
                    if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
                        return false;
                    else
                        return true;
                }
                else
                {
                    // If it's not the first character, then it must be a digit or backspace
                    if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
                        return false;
                    else
                        return true;
                }
            }
            else
            {
                // Test first character - either text is blank or the selection starts at first character.
                if (txt.Text == "" || txt.SelectionStart == 0)
                {
                    // If the first character is a minus or digit, AND
                    // if the text does not contain a minus OR the selected text DOES contain a minus.
                    if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
                        return false;
                    else
                    {
                        // If the first character is a decimal point or digit, AND
                        // if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
                        if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
                            return false;
                        else
                            return true;
                    }
                }
                else
                {
                    // If it's not the first character, then it must be a digit or backspace OR
                    // a decimal point AND
                    // if the text does not contain a decimal point or the selected text does contain a decimal point.
                    if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
                        return false;
                    else
                        return true;
                }

            }
        }

答案 9 :(得分:0)

检查值是否为double:

private void button1_Click(object sender, EventArgs e)
{

    if (!double.TryParse(textBox1.Text, out double myX))
    {
        System.Console.WriteLine("it's not a double ");
        return;
    }
    else 
        System.Console.WriteLine("it's a double ");
}

答案 10 :(得分:0)

我知道这是一个古老的问题,但我想我还是应该提出答案。

以下代码片段循环遍历文本的每个字符,并使用IsNumber()方法(如果该字符是数字,则返回true,否则返回false),以检查所有字符是否都是数字。如果都是数字,则该方法返回true。如果不是,则返回false。

using System;

private bool ValidateText(string text){
    char[] characters = text.ToCharArray();

    foreach(char c in characters){
        if(!char.IsNumber(c))
            return false;
    }
    return true;
}

答案 11 :(得分:0)

使用正则表达式如下。

if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
 MessageBox.show("add content");
} else {
 MessageBox.show("add content");
}