如何验证文本框的5个字符输入,即前3个字符仅为字母,后2个字符为数字c#



我需要创建一个方法来检查文本框中的5个字符输入。前3个字符应该是字母,后2个字符应该为数字。

这是我当前的代码:

public void checkInput(String s) {
if (CheckInputString(s)) {
//To Check if the first 3 characters are letters and check last 2 characters if numbers
}
else {
//Invalid
}

请帮忙。

您可以使用RegEx〔A-Za-z〕{3}-匹配3个alpha[0-9]{2}-匹配2个数字

使用给定的regex在线测试您的输入https://regex101.com/r/fF4zG9/5

Regex temp = new Regex("^[A-Za-z]{3}[0-9]{2}$");
string yourVal = "asd12";
if(temp.IsMatch(yourVal))
{
//Matches
}
else
{
//Fails
}

您可以使用正则表达式来检查字符串。

^[a-zA-Z]{3}[0-9]{2}$

你的代码可能是这样的:

public bool CheckInputString(string s)
{
System.Text.Regex regex = new System.Text.Regex("^[a-zA-Z]{3}[0-9]{2}$");
return regex.IsMatch(s);
}

一种方法是简单地验证字符串上的每个需求,如果它们都通过,则返回true

public static bool IsValid(string input)
{
return input != null &&                      // Not null
input.Length == 5 &&                  // Is 5 characters
input.Take(3).All(char.IsLetter) &&   // First three are letters
input.Skip(3).All(char.IsDigit);      // The rest are numbers
}

最新更新