C# 正在验证仅用于数字输入的文本框字段。

C# 正在验证仅用于数字输入的文本框字段。,c#,validation,textbox,C#,Validation,Textbox,我创建了一个基于表单的程序,需要一些输入验证。我需要确保用户只能在距离文本框中输入数值 到目前为止,我已检查文本框中是否有内容,但如果它有值,则应继续验证输入的值是否为数字: else if (txtEvDistance.Text.Length == 0) { MessageBox.Show("Please enter the distance"); } else if (cboAddEvent.Text //is numeric)

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

到目前为止,我已检查文本框中是否有内容,但如果它有值,则应继续验证输入的值是否为数字:

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");
        }
您可以尝试将字符串解析为整数并返回指示操作成功或失败的布尔结果的方法

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

下面是另一个简单的解决方案

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

我有一个多用途的扩展:

    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;
    }
它适用于其他数据类型。您可以通过客户端的javascript或使用文本框中的某些正则表达式验证程序来完成

Javascript
scripttype=“text/javascript”language=“javascript”>
功能验证仅限Enumbers(e){
var unicode=e.charCode?e.charCode:e.keyCode;
如果((unicode==8)| |(unicode==9)| |(unicode>47&&unicode<58)){
返回true;
}
否则{
window.alert(“此字段仅接受数字”);
返回false;
}
}
文本框(带有固定的ValidationExpression)
如果要防止用户在文本框中输入信息时输入非数值,可以使用事件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            
        }
如果用户使用鼠标(右键单击/粘贴)将信息粘贴到文本框中,则此解决方案不起作用。在这种情况下,您应该添加额外的验证。

您可以这样做

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

我同意Int.TryParse,但也可以使用Regex

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

这里有一个解决方案,它允许只带负号的数字或带负号和小数点的小数。以前的大多数答案没有考虑选定的文本。如果您将文本框的ShortcutsEnabled更改为false,那么您也不能将垃圾粘贴到文本框中(它会禁用右键单击)。有些解决方案允许您在减号之前输入数据。请确认我抓到了所有东西

private bool decimallony\u按键(文本框txt,bool numeric,按键事件参数e)
{
如果(数字)
{
//测试第一个字符-文本为空或选择从第一个字符开始。
如果(txt.Text==“”| | txt.SelectionStart==0)
{
//如果第一个字符是负号或数字,并且
//如果文本不包含负号或选定文本包含负号。
如果((e.KeyChar='-'| | char.IsDigit(e.KeyChar))&(!txt.Text.Contains(“-”)| | txt.SelectedText.Contains(“-”))
返回false;
其他的
返回true;
}
其他的
{
//如果不是第一个字符,则必须是数字或退格
if(char.IsDigit(e.KeyChar)| | e.KeyChar==Convert.ToChar(Keys.Back))
返回false;
其他的
返回true;
}
}
其他的
{
//测试第一个字符-文本为空或选择从第一个字符开始。
如果(txt.Text==“”| | txt.SelectionStart==0)
{
//如果第一个字符是负号或数字,并且
//如果文本不包含负号或选定文本包含负号。
如果((e.KeyChar='-'| | char.IsDigit(e.KeyChar))&(!txt.Text.Contains(“-”)| | txt.SelectedText.Contains(“-”))
返回false;
其他的
{
//如果第一个字符是小数点或数字,以及
//如果文本不包含小数点或选定文本包含小数点。
如果((e.KeyChar='.| | char.IsDigit(e.KeyChar))&(!txt.Text.Contains(“.”| | txt.SelectedText.Contains(“.”))
返回false;
其他的
返回true;
}
}
其他的
{
//如果不是第一个字符,则必须是数字或退格或空格
//小数点和
//如果文本不包含小数点或选定文本包含小数点。
if(char.IsDigit(e.KeyChar)| | e.KeyChar==Convert.ToChar(Keys.Back)| | | | | | | | | | | | | | | | | | | | |
返回false;
其他的
返回true;
}
}
}

要检查该值是否为双精度:

private void button1_Click(object sender, EventArgs e)
{

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

我知道这是个老生常谈的问题,但我想无论如何我都应该给出我的答案

下面的代码段遍历文本的每个字符,并使用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;
}
使用正则表达式如下

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

您所说的数字是什么意思?只有数字?有效的小数?我的意思是,大于0的值和整数,典型的体育赛事距离非常类似的问题,可能是重复的。我敢肯定这是一个窗口形式
private void button1_Click(object sender, EventArgs e)
{

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

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

    foreach(char c in characters){
        if(!char.IsNumber(c))
            return false;
    }
    return true;
}
if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
 MessageBox.show("add content");
} else {
 MessageBox.show("add content");
}