7

I would like to know how I would be able to allow only numbers and a "-" minus sign in a textbox?

Here is coding that I can already allow only numbers:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}
CareTaker22
  • 1,260
  • 3
  • 18
  • 36
  • 2
    So do you mean a positive or negative integer like 1234 or -1234 or do you mean something that has a "-" sign in it like 800-555-5555? – Jason Hughes Jul 28 '15 at 12:56

6 Answers6

10

Just add the - to your regex character group, in a position that's not making a range of characters:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9-]+");
    e.Handled = regex.IsMatch(e.Text);
}
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • 1
    @loli I think this function runs on a character by character basis, it's intended to stop the characters even making it into the textbox, so yes - it would. You'd need to have different validation elsewhere to handle the whole actual value in the box, depending on what's actually acceptable. Chances are that's going to be the OP's next problem, but it's not actually specified in the Q. – James Thorpe Jul 28 '15 at 12:57
  • I don't think PreviewTextInput is called after every character. The documentation on this event is not very clear. – loli Jul 28 '15 at 13:23
2

I think you want something like this

^[0-9-]*$

It will match any digit any time and n no of dashes and will ignore any other character

blue
  • 932
  • 7
  • 9
2

[^-]+[^0-9]+ should prevent any input that's not an integer or a negative integer.

loli
  • 1,058
  • 8
  • 14
  • I think is not correct because if the value is 50 pressing the minus sign it will become -50 but if you press again minus it will become -50----- – Marco Jul 12 '18 at 15:13
1

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

Then inside that set the e.Handled if the text isn't allowed.

e.Handled = !IsTextAllowed(e.Text);

I use a simple regex in IsTextAllowed to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here (code excerpted):

// Use the DataObject.Pasting Handler 
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}
DeshDeep Singh
  • 1,817
  • 2
  • 23
  • 43
1
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {

        if (!char.IsDigit(e.Text, e.Text.Length - 1))
        {
            if(e.Text.Length != 0 || (e.Text.Length == 0 && e.Substring(e.Text.Length - 1) != "-"))
                e.Handled = true;

        }
    }
darson1991
  • 406
  • 6
  • 18
0

Here is the best solution for numeric Textbox and This is answer by Answer!

    private bool IsOKForDecimalTextBox(char theCharacter, TextBox theTextBox)
{
    // Only allow control characters, digits, plus and minus signs.
    // Only allow ONE plus sign.
    // Only allow ONE minus sign.
    // Only allow the plus or minus sign as the FIRST character.
    // Only allow ONE decimal point.
    // Do NOT allow decimal point or digits BEFORE any plus or minus sign.

    if (
        !char.IsControl(theCharacter)
        && !char.IsDigit(theCharacter)
        && (theCharacter != '.')
        && (theCharacter != '-')
        && (theCharacter != '+')
    )
    {
        // Then it is NOT a character we want allowed in the text box.
        return false;
    }



    // Only allow one decimal point.
    if (theCharacter == '.'
        && theTextBox.Text.IndexOf('.') > -1)
    {
        // Then there is already a decimal point in the text box.
        return false;
    }

    // Only allow one minus sign.
    if (theCharacter == '-'
        && theTextBox.Text.IndexOf('-') > -1)
    {
        // Then there is already a minus sign in the text box.
        return false;
    }

    // Only allow one plus sign.
    if (theCharacter == '+'
        && theTextBox.Text.IndexOf('+') > -1)
    {
        // Then there is already a plus sign in the text box.
        return false;
    }

    // Only allow one plus sign OR minus sign, but not both.
    if (
        (
            (theCharacter == '-')
            || (theCharacter == '+')
        )
        && 
        (
            (theTextBox.Text.IndexOf('-') > -1)
            ||
            (theTextBox.Text.IndexOf('+') > -1)
        )
        )
    {
        // Then the user is trying to enter a plus or minus sign and
        // there is ALREADY a plus or minus sign in the text box.
        return false;
    }

    // Only allow a minus or plus sign at the first character position.
    if (
        (
            (theCharacter == '-')
            || (theCharacter == '+')
        )
        && theTextBox.SelectionStart != 0
        )
    {
        // Then the user is trying to enter a minus or plus sign at some position 
        // OTHER than the first character position in the text box.
        return false;
    }

    // Only allow digits and decimal point AFTER any existing plus or minus sign
    if  (
            (
                // Is digit or decimal point
                char.IsDigit(theCharacter)
                ||
                (theCharacter == '.')
            )
            &&
            (
                // A plus or minus sign EXISTS
                (theTextBox.Text.IndexOf('-') > -1)
                ||
                (theTextBox.Text.IndexOf('+') > -1)
            )
            &&
                // Attempting to put the character at the beginning of the field.
                theTextBox.SelectionStart == 0
        )
    {
        // Then the user is trying to enter a digit or decimal point in front of a minus or plus sign.
        return false;
    }

    // Otherwise the character is perfectly fine for a decimal value and the character
    // may indeed be placed at the current insertion position.
    return true;
}

and Then Call This Function in the Key Press Event Like As

public void Allow_Only_Numeric(object sender, KeyPressEventArgs e)
    {
        try
        {

            TextBox textbox = (TextBox)sender;
            Console.WriteLine(textbox.Text);
            if(IsOKForDecimalTextBox(e.KeyChar,textbox) == true)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
ABDUL REHMAN
  • 73
  • 1
  • 7