正则表达式适用于RegularExpressionValidator但在Regex.IsMatch上返回false

时间:2013-03-26 11:41:56

标签: c# webforms

我有以下RegularExpressionValidator:

<asp:RegularExpressionValidator CssClass="Validator_alert" ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtPassword"
        ErrorMessage="Dit kodeord skal være mindst 6 tegn langt og indholde et tal, et stort bogstav og lille bogstav. Kodeordet må ikke indeholde tegnene &amp; og &#37;."
        ValidationExpression="(?!^[0-9]*$)(?!^[a-z])(?!^[A-Z]*$)^([a-zA-Z0-9!@_:;+]{6,50})$"
        SetFocusOnError="true" />

以下代码检查表达式以及:

string pattern = @"(?!^[0-9]*$)(?!^[a-z])(?!^[A-Z]*$)^([a-zA-Z0-9!@_:;+]{6,50})$";

                Boolean meetsRequirements = false;

                meetsRequirements = System.Text.RegularExpressions.Regex.IsMatch(pattern, txtPassword.Value);
                meetsRequirements = System.Text.RegularExpressions.Regex.IsMatch(pattern, txtPasswordRepeat.Value);

                return meetsRequirements;

txtPassword.Value和txtPasswordRepeat.Value中的值通过前端的测试(RegularExpressionValidator)时,为什么IsMatch返回false?

1 个答案:

答案 0 :(得分:1)

Regex.IsMatch有2个参数 - 第一个是输入文本,第二个是模式。您的参数顺序不正确。使用:

string pattern = @"(?!^[0-9]*$)(?!^[a-z])(?!^[A-Z]*$)^([a-zA-Z0-9!@_:;+]{6,50})$";

Boolean meetsRequirements = false;

meetsRequirements = System.Text.RegularExpressions.Regex.IsMatch(txtPassword.Value, pattern);
meetsRequirements = System.Text.RegularExpressions.Regex.IsMatch(txtPasswordRepeat.Value, pattern);

return meetsRequirements;

最有可能你应该使用以下方法检查两个输入是否正确:

meetsRequirements = 
    System.Text.RegularExpressions.Regex.IsMatch(txtPassword.Value, pattern)
    && System.Text.RegularExpressions.Regex.IsMatch(txtPasswordRepeat.Value, pattern);