Skip to main content
 首页 » 编程设计

c#之添加字符串长度验证

2024年02月06日20jillzhang

我正在为我的 text 字符串添加验证。它允许 string 和 integer 值,这是正确的,但我希望我的 text 长度大于 4 个字符。我添加了 text.Length > 4 但这不会在输入 2 字符串时添加任何验证。有什么建议吗?

public bool IsStringInvalid(string text) 
        { 
            if (String.IsNullOrEmpty(text)) 
            { 
                if (text != null && !Regex.IsMatch(text, textCodeFormat) && text.Length > 4) 
                { 
                    return true; 
                } 
            } 
            return false; 
        } 

请您参考如下方法:

您的方法称为 IsStringLengthInvalid,这意味着它应该为无效字符串返回 true。现在,您似乎正试图仅对有效字符串返回 true。

像这样的东西应该可以工作:

    public bool IsStringInvalid(string text) 
    { 
        return string.IsNullOrEmpty(text) || 
            text.Length <= 4 || 
            !Regex.IsMatch(text, textCodeFormat); 
    }