How to allow numbers and minus "-" in the text box

I would like to know how I can only allow numbers and the minus sign in the text box?

Here is the code that I can already resolve only numbers:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); } 
+6
source share
5 answers

Just add - to your regex character group in a position that doesn't make a range of characters:

 private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[^0-9-]+"); e.Handled = regex.IsMatch(e.Text); } 
+9
source

I think you want something like this

 ^[0-9-]*$ 

It will match any digit at any time and n there is no dash and will ignore any other character

+2
source

[^-]+[^0-9]+ should interfere with any input that is not an integer or negative integer.

+2
source

Add a preview text input event. For example: <TextBox PreviewTextInput="PreviewTextInput" /> .

Then inside this set is e.Handled if the text is not allowed.

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

I use a simple regular expression in IsTextAllowed to see if they allow me what they typed. In my case, I just want to allow numbers, periods, 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 the insertion of incorrect data, turn DataObject.Pasting="TextBoxPasting" DataObject.Pasting DataObject.Pasting="TextBoxPasting" , as shown here (the code is written out):

 // 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(); } } 
+1
source
 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; } } 
+1
source

All Articles