如何验证文本框?

时间:2012-11-15 05:48:08

标签: c#

public bool ValidateText(String strName)
{
    try
    {
        // declaring string variable here
        String strpattern;
        // regex pattern setting 
        strpattern = @"^[a-zA-Z][a-zA-Z0-9']{20}$";
        // checking for matching with given string here
        Regex regex = new Regex(strpattern);
        // returns status here
        return regex.IsMatch(strName);
    }
    catch (Exception ex)
    {
        return false;
    }
}

当我尝试插入名称如q'''''''''''''''时它返回字符串值而不是布尔值。 PLZ,让我知道我在这个特殊功能中出错了吗?

我需要验证TextBox中的文本。换句话说,TextBox中的Text如果与给定的pattern不匹配则应该转换为匹配的字符串。应检查每个用户输入的字符或用户粘贴的字符集。

2 个答案:

答案 0 :(得分:0)

也许这就是你要找的东西。

        public bool ValidateText(String strName)
        {
            try
            {
                // declaring string variable here
                String strpattern;
                // regex pattern setting 
                strpattern = @"^[a-zA-Z][a-zA-Z0-9']{20}$";
                // checking for matching with given string here
                if (!Regex.Match(strName, strpattern))
                {
                  return false;
                }
                else
                  return true;

            }
            catch (Exception ex)
            {
                ////handle exception
            }
        }

答案 1 :(得分:0)

从您的问题中除了问题标题

之外没有任何其他描述
  

如何验证文本框?

我能从中理解和您的代码是您正在尝试使用正则表达式模式验证输入文本框字段吗?

您的代码似乎完全是为此而编写的。

我认为你没有得到它正确是你正在使用的正则表达式模式!

使用thisthis测试正则表达式。

我还建议您read this.

相关问题