c# - 必须同时包含数字和字母的文本框?

标签 c# textbox alphanumeric

我想知道有什么方法可以确保用户在文本框中输入数字和字母,如果不提示消息?我有它如下:

if(!Regex.IsMatch(string, @"^[a-zA-Z]+$") && !Regex.IsMatch(string, @"^[1-9]+$"))
{  
    MessageBox.Show("Please Enter both numbers and letters");
    return;
}

所以这里我想说的是,如果字符串中没有字母AND如果字符串中没有数字,则提示错误。但是,如果你输入所有字母(或数字),没有错误提示,所以我想知道是否有办法做到这一点。我研究了这些问题,除了如何允许某些字符外,没有发现任何其他内容。

最佳答案

此时,您的代码显示

Show the message if the string is not entirely made of letters, and not entirely made of numbers

这几乎与您所追求的完全相反。

要修复它,您需要将“not entirely made of”改为“doesn't contain”,将“and”改为“or”:

if(!Regex.IsMatch(string, @"[a-zA-Z]") || !Regex.IsMatch(string, @"[1-9]"))
{  
    MessageBox.Show("Please Enter both numbers and letters");
    return;
}

正则表达式现在只查找单个字母或数字,and 现在是 or

如果您想确保您的输入包含字母或数字,您可以单独执行以下步骤:

if(Regex.IsMatch(string, @"[^a-zA-Z0-9]"))
{  
    MessageBox.Show("Please Enter only numbers and letters");
    return;
}

关于c# - 必须同时包含数字和字母的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631373/

相关文章:

c# - C# 中 N 个 SortedLists<T> 相交

c# - 如何在文本框中显示注册表项 C#

javascript - 在 IE 中检测 texbox 清除事件。单击 IE 特定的清除框时,如何清除 IE (Internet Explorer) 中的输入类型 ="text"(文本框)?

JQuery ajax 调用不接受字母数字参数!

c# - ASP.NET:隐藏 CheckBoxList 控件中的 CheckBox 项

c# - 将 Dictionary<string, string> 转换为 Dictionary<string, object> 的最简单方法是什么?

c# - 添加引用失败。用户取消了保存对话框 (OLE_E_PROMPSAVECANCELLED)

jquery - 如何使用 jQuery 获取文本框数组中的元素数量?

javascript - 正则表达式允许单词之间使用标点符号和空格

java - 一起生成随机字母和数字