您应该使用两个独立的验证器,一个用于检查长度,另一个用于检查最小所需字符数(这样您可以获得每个检查的两个独立错误消息)。
例如:
<asp:TextBox ID="MyPasswordField" runat="server" TextMode="Password"></asp:TextBox>
<!-- Add validator for minimum length requirement -->
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordMinLengthValidator" ValidationExpression="^[\s\S]{8,}$" runat="server" ErrorMessage="Password must be at least 8 characters long."></asp:RegularExpressionValidator>
<!-- Add validator for minimum required characters -->
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordRequiredCharacterValidator" ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$" runat="server" ErrorMessage="Must contain at least one uppercase letter, one lowercase letter, and one number."></asp:RegularExpressionValidator>
如果您还需要验证密码的最大长度,您可以将第一个验证器的正则表达式更改为以下内容:
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordMinMaxLengthValidator" ValidationExpression="^[\s\S]{8,40}$" runat="server" ErrorMessage="Password must be between 8 and 40 characters long."></asp:RegularExpressionValidator>
如果你需要验证至少一个特殊字符出现过,那么可以使用下面这个正则表达式进行第二次验证(至少包含以下一种字符:<space>@#$%^&?,;:_|{}=+-!.*()[]~):
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordRequiredCharacterValidator" ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&?,;:_|~{}=\+\-\!\.\*\(\)\[\] ]).+$" runat="server" ErrorMessage="Must contain at least one uppercase letter, one lowercase letter, one number, and one special character."></asp:RegularExpressionValidator>
^[\s\S]{6,}$
。 - Adam