【问题标题】:How to allow backspace and space when validating letters?验证字母时如何允许退格和空格?
【发布时间】:2018-06-04 00:59:37
【问题描述】:

我使用的代码是这样的:

If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) < 90 _
And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
    MessageBox.Show("Please enter letters only")
    e.Handled = True
End If

在VB中验证字母时如何允许退格和空格?

【问题讨论】:

  • 你确定这是正确的:Or Asc(e.KeyChar) &lt; 90?您不是要检查它是否大于 大于 90?
  • 是的,任何好的 UI 的一个关键元素是责骂和惩罚用户的每一次错误击键。不允许有错别字。

标签: .net vb.net validation backspace


【解决方案1】:

退格的字符代码是 8,空格的字符代码是 32,所以你的代码应该是:

If (Asc(e.KeyChar) < 65 OrElse Asc(e.KeyChar) < 90) _
AndAlso (Asc(e.KeyChar) < 97 OrElse Asc(e.KeyChar) > 122) _
AndAlso Asc(e.KeyChar) <> 8 AndAlso Asc(e.KeyChar) <> 32 Then
    MessageBox.Show("Please enter letters only")
    e.Handled = True
End If

请注意,我使用AndAlso,在遇到第一个False 时停止评估。

【讨论】:

  • 既然您切换到AndAlso,您可能还想使用OrElse ;)。此外,请考虑将 Or/OrElse 检查与括号分组。这样更容易阅读,但您也可以确保它正确执行。
猜你喜欢
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
相关资源
最近更新 更多