Allow only letters for input

How to filter non-letter keys with a virtual keyboard?

The following method works only for the Latin alphabet, for unhappiness:

public static bool IsLetter(int val) { return InRange(val, 65, 90) || InRange(val, 97, 122) || InRange(val, 192, 687) || InRange(val, 900, 1159) || InRange(val, 1162, 1315) || InRange(val, 1329, 1366) || InRange(val, 1377, 1415) || InRange(val, 1425, 1610); } public static bool InRange(int value, int min, int max) { return (value <= max) & (value >= min); } 
+2
source share
1 answer

I think you can use Regex for this, fired the KeyUp event of your TextBox - when the user issues a key, the method checks to see if it suits your requirements. It might look like this:

 myTextbox.KeyUp += myTextbox_KeyUp; // somewhere in Page Constructor private void myTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { Regex myReg = new Regex(@"\d"); if (myReg.IsMatch(e.Key.ToString()) || e.Key == Key.Unknown) { string text = myTextbox.Text; myTextbox.Text = text.Remove(text.Length - 1); myTextbox.SelectionStart = text.Length; } } 

In the above code, any keystrokes or Unknown key are checked (debug to find out which ones) - if the user presses a number, then the last entered char will delete the form text. You can also define your Regex differently, for example, allowing only letters:

 Regex myReg = new Regex(@"^[a-zA-Z]+$"); if (!myReg.IsMatch(e.Key.ToString()) || e.Key == Key.Unknown) { // the same as above } 

I assume that you have already set the area of your keyboard.

EDIT - non-Latin keyboard

The above code will not succeed, if you use, for example, Cyrillic, then e.Key will be Key.Unknown, which causes a small problem. But I managed to cope with this task by checking the last character entered, if it is not equal to AlfaNumeric \W or the digit \d , deleting it - works fine even with strange characters:

 private void myTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { string added = myTextbox.Text.ElementAt(myTextbox.Text.Length - 1).ToString(); Regex myReg = new Regex(@"[\W\d]"); if (myReg.IsMatch(added)) { string text = myTextbox.Text; myTextbox.Text = text.Remove(text.Length - 1); myTextbox.SelectionStart = text.Length; } } 
+2
source

Source: https://habr.com/ru/post/1242236/


All Articles