对允许字母数字和下划线"_"的文本框进行验证 [英] Validation to textbox which allows alphanumaric and underscore "_"

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

问题描述



我正在尝试通过在WPF中的以下方法中使用正则表达式来验证允许字母数字和下划线"_"的文本框.
但是它允许所有值.我需要对该代码进行任何修改,或者需要任何可用的替代方法...请对此进行研究.
谢谢.

Hi,

I am trying to validate textbox which allows alphanumaric and underscore "_" by using regularexpressions in following method in WPF.
But it allows all the values. I need any modifications in this code or any alternative method that is available...Please look into this.
Thanks.

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    if (alphaNumericCheck(e.ToString()))
    {
        e.Handled = true;
    }
    else
        e.Handled = false;
}

private bool alphaNumericCheck(string p)
{
    if (regex.IsMatch(p))
        return true;
    else
        return false;
}

推荐答案

要允许字母数字和下划线,请将您的正则表达式更改为[^ a-zA-Z_0-9]

像这样:

To allow alphanumeric and underscore change your regular expression to [^a-zA-Z_0-9]

Like so:

string expression = "[^a-zA-Z_0-9]";
string sIn = "SomeText 900_009";

sIn = Regex.Replace(sIn, expression, "");  



另外,需要包含using System.Text.RegularExpressions;才能使用正则表达式.

Replace方法中的第三个参数是您希望替换与正则表达式不匹配的任何字符的字符串.

上面代码的输出为SomeText900_009



Also, using System.Text.RegularExpressions; needs to be included to use Regex.

The third parameter in the Replace method is the string you wish to replace any characters that don''t match your regular expression.

The output of the above code would be SomeText900_009


sankar.cs写道:
sankar.cs wrote:

if(alphaNumericCheck (e.ToString()))

if (alphaNumericCheck(e.ToString()))



当然e.ToString()将是"System.Windows.Controls.TextChangedEventArgs"

艾伦.



Surely e.ToString() will be "System.Windows.Controls.TextChangedEventArgs"

Alan.


您好,就像上面的评论一样,您的Regex应该有问题,您没有提供它.试试看,让我知道.
Hello, like the comment above stated, it should be a problem with your Regex which you did not provide. Give this a try and let me know.
private bool alphaNumericCheck(string p)
{
    return new Regex("^[A-Za-z_0-9]").IsMatch(p);
}



显然忘记了数字+较小的更改.

谢谢
AnılYıldız.



Apperantly forgot about numbers + minor changes.

Thank you,
Anıl Yıldız.


这篇关于对允许字母数字和下划线"_"的文本框进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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