I have this code:
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9]+"); // Regex that matches disallowed text
return !regex.IsMatch(text);
}
private void TextboxClientID_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
This allows whitespaces in the textbox, how to prevent from inserting whitespaces too?
In regex, the \s modifier translates to [\r\n\t\f ], which means no newline characters, no tab characters, no form feed characters (used by printers to start a new page), and no spaces.
So you can use the regex [^\\s] (you have to use \\ in order to make a single \, which will then translate to \s finally. If you just use \s, it will translate to s character literal.
The beginning and ending ^ and $ characters match the beginning and end of the string respectively.
So, you could use the regex ^[^0-9\\s]+$. Here is a breakdown of what it does:
^ matches the beginning of the string.[], which will match any single character in that group[], we have ^0-9\\s:
^ character makes sure that no single character inside of the [] will be matched (switches it from any single character to no single character), none of the following should be true0-9 part matches any number between 0 and 9\\s part creates literally \s. \s matches any whitespace character+ matches the group inclosed in [] between 1 and infinite times$ matches the end of the stringYour code could be:
private static bool IsTextAllowed(string text){
Regex regex = new Regex("^[^0-9\\s]+$");
return !regex.IsMatch(text);
}
Here's a regex101 test: https://regex101.com/r/aS9xT0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With