验证带有字母数字的文本框 [英] Validation for a text box with alphanumeric

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

问题描述

大家好,



我是C#的新手。我需要验证文本框。文本框可能包含字母数字,但不允许使用数字。我怎样才能做到这一点。它在C#windows应用程序中。



示例:12Abc ---------允许

:12546 ---- ------不允许

:Asd23lk --------允许





谢谢



关注

解决方案

如果您不想允许任何其他字符输入除外TextBox中的字母数字字符,然后您可以在TextBox的KeyPress事件上执行此操作。

在KeyPress事件中,您需要检查输入的字符是字母还是数字。



Char.IsLetterOrDigit(e .KeyChar)

如果是,那么按下按键设置

e.Handled = false



否则,不要通过设置e.Handled = true来允许按键

除了字母数字字符外,通常还应该允许退格字符以及字母数字字符,以便如果用户输入错误,用户可以删除任何错误的字符。为了做到这一点,你需要在if块中再添加一个条件为

 private void textBox_KeyPress(object sender,KeyPressEventArgs e)
{
if(Char.IsLetterOrDigit(e.KeyChar)//只允许任何字母或数字
|| e.KeyChar =='\ b')//允许BackSpace字符
{
e.Handled = false;
}
其他
{
e.Handled = true;
}
}


试试这个



  public   bool  IsAlphaNumeric( string  inputString)
{
Regex reg = new 正则表达式( ^(\d)* + [A-ZA-Z] +(\d)* + *

)。
if (reg.IsMatch(inputString))
return ;
else
return false < /跨度>;
}


Hi All,

I am new to C#. I need a validation for a text box. Text box may contain alphanumeric but only numbers is not allowed. How can i do that. It is in C# windows application.

Example : 12Abc --------- Allowed
: 12546---------- Not allow
: Asd23lk-------- Allow


Thanks

Regards

解决方案

If you don't want to allow any other characters entry except for the alphanumeric characters in a TextBox, then you can do this on the KeyPress event of a TextBox.
In the KeyPress Event, you need to check whether the entered character is either a Letter or a Digit.

Char.IsLetterOrDigit(e.KeyChar)
If yes, then allow the Key pressing by setting
"e.Handled = false"

Otherwise, don't allow the Key pressing by setting "e.Handled = true"
In addition to the alphanumeric characters, generally one should allow the backspace character too along with the alphanumeric characters so that the user can remove any wrong character if he entered by mistake. In order to do that, you need to add one more condition in the if block as

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsLetterOrDigit(e.KeyChar)     // Allowing only any letter OR Digit
            ||e.KeyChar == '\b')                 // Allowing BackSpace character
    {
        e.Handled = false;
    }
    else
    {
        e.Handled = true;
    }
} 


Try this

public bool IsAlphaNumeric(string inputString)
{
Regex reg = new Regex("^(\d)*+[A-Za-z]+(\d)*+.*


"); if (reg.IsMatch(inputString)) return true; else return false; }


这篇关于验证带有字母数字的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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