[c#] Validating a Textbox field for only numeric input.

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.

So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value 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");
        }

This question is related to c# validation textbox

The answer is


I know this is an old question but I figured out I should pitch my answer anyways.

The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns 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;
}

You can do it by javascript on client side or using some regex validator on the textbox.

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>

Textbox (with fixed 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> 

If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:

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            
        }

This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.


Here's a solution that allows either numeric only with a minus sign or decimal with a minus sign and decimal point. Most of the previous answers did not take into account selected text. If you change your textbox's ShortcutsEnabled to false, then you can't paste garbage into your textbox either (it disables right-clicking). Some solutions allowed you to enter data before the minus. Please verify that I've caught everything!

        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;
                }

            }
        }

Use Regex as below.

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

Here is another simple solution

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

You can do this way

   // 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
    }     

To check if the value is a double:

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 ");
}

        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;
        }

I agree with Int.TryParse but as an alternative you could use Regex.

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

I have this extension which is kind of multi-purpose:

    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;
    }

It works for other data types. Should work fine for what you want to do.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox