只允许输入字母 [英] Allowing only letters for input

查看:41
本文介绍了只允许输入字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何过滤虚拟键盘中的非字母键?

How to filter non-letter keys from the virtual keyboard?

以下方法仅适用于拉丁字母表,不幸的是:

The following method works just for latin alphabet, for unfortune:

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

推荐答案

我认为您可以为此使用 Regex,在 TextBox 的 KeyUp 事件中触发 - 当用户释放键时,该方法将检查他按下的内容是否符合您的要求.它可以看起来像这样:

I think you can use Regex for this, fired in KeyUp event of your TextBox - when user releases key, the method will check if what he pressed fits your requirements. It can look for example 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;
    }
}

上面的代码检查是否有任何按下的数字或未知键(调试以查看它们是哪些)-如果用户按下数字,则最后输入的字符将从表单文本中删除.您还可以以不同的方式定义您的正则表达式,例如只允许字母:

The code above checks for any digit pressed or Unknown key (debug to see which are they) - if the user pressed digit, then the last entered char is removed 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 }

我假设您已经设置了 范围.

编辑 - 非拉丁键盘

如果您使用例如西里尔字母,则上面的代码不会成功,那么 e.Key 将是 Key.Unknown,这会导致一些问题.但是我已经设法通过检查输入的最后一个字符来处理这个任务,如果它是非字母数字 \W 或数字 \d,删除它 - 即使使用奇怪的字符也能很好地工作:

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

EDIT - non latin keyboard

The code above wouldn't grant success if you use for example cyrillic, then e.Key will be Key.Unknown which causes a little problem. But I've managed to handle this task with checking the last character entered if it is nonAlphaNumeric \W or digit \d, delete it- works quite fine even with strange chars:

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

这篇关于只允许输入字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆