我正在使用缺口(给出名字)。
当用户注册时,您必须输入您的昵称,相同,它不能包含符号(下划线除外),只能包含数字和字母。
我使用KeyPress
用户名的TextBox
事件:
private bool Handled = false;
private void Username_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar)) this.Handled = false;
else
{
if (e.KeyChar == '\b') this.Handled = false; //Backspace key
else
{
if (e.KeyChar == '_' && !((TextBox)sender).Text.Contains("_") && ((TextBox)sender).Text.Length > 0) this.Handled = false;
else this.Handled = true;
}
}
e.Handled = Handled;
}
这段代码可以防止符号(与“_”不同),内容以“_”开头并使用多个下划线“H_E_L_L_O”写入,但是它们需要防止下划线可以在末尾使用,我的意思是:
允许:Hell_o
预防:Hello_
这可能吗?
修改
我也使用了
String.Last()
,但结果是一样的:
if(TextBox.Text.Last() == '_')
{
// Handled = true;
}
答案 0 :(得分:6)
除非你能读懂用户的想法,否则你不能这样做:)毕竟,用户可能想要在你的例子中添加Hell_o
,但要键入他们首先需要键入“Hell_”所以你在那一点上无法阻止他们。您可能要做的最好的事情是处理UserName控件上的“Validating”事件。
private void UserName_Validating(object sender, CancelEventArgs e) {
errorProvider1.SetError(UserName, "");
if (UserName.Text.EndsWith("_")) {
errorProvider1.SetError(UserName, "Stuff is wrong");
}
}
然后在“注册”按钮单击或其他任何内容,检查该控件是否(或您关心的任何控件)出错。