问题描述
这是到目前为止我C#应用程序中密码的流利验证
RuleFor(request => request.Password)
.NotEmpty()
.MinimumLength(8)
.Matches("[A-Z]+").WithMessage("'{PropertyName}' must contain one or more capital letters.")
.Matches("[a-z]+").WithMessage("'{PropertyName}' must contain one or more lowercase letters.")
.Matches(@"(\d)+").WithMessage("'{PropertyName}' must contain one or more digits.")
.Matches(@"[""!@$%^&*(){}:;<>,.?/+\-_=|'[\]~\\]").WithMessage("'{ PropertyName}' must contain one or more special characters.")
.Matches("(?!.*[£# “”])").WithMessage("'{PropertyName}' must not contain the following characters £ # “” or spaces.")
.Must(pass => !blacklistedWords.Any(word => pass.IndexOf(word,StringComparison.OrdinalIgnoreCase) >= 0))
.WithMessage("'{PropertyName}' contains a word that is not allowed.");
以下部分当前不起作用
.Matches("(?!.*[£# “”])").WithMessage("'{PropertyName}' must not contain the following characters £ # “” or spaces.")
例如,当密码为“ Hello12!#”时,不返回验证错误。 £#“”和密码中不应包含空格,如果存在任何空格,则验证将失败,并且“ {PropertyName}”不得包含以下字符£#“”或空格。错误消息。
如何修改它以使其正常工作?
解决方法
您可以使用
RuleFor(request => request.Password)
.NotEmpty()
.MinimumLength(8)
.Matches("[A-Z]").WithMessage("'{PropertyName}' must contain one or more capital letters.")
.Matches("[a-z]").WithMessage("'{PropertyName}' must contain one or more lowercase letters.")
.Matches(@"\d").WithMessage("'{PropertyName}' must contain one or more digits.")
.Matches(@"[][""!@$%^&*(){}:;<>,.?/+_=|'~\\-]").WithMessage("'{ PropertyName}' must contain one or more special characters.")
.Matches("^[^£# “”]*$").WithMessage("'{PropertyName}' must not contain the following characters £ # “” or spaces.")
.Must(pass => !blacklistedWords.Any(word => pass.IndexOf(word,StringComparison.OrdinalIgnoreCase) >= 0))
.WithMessage("'{PropertyName}' contains a word that is not allowed.");
注意:
-
.Matches(@"[][""!@$%^&*(){}:;<>,.?/+_=|'~\\-]")
-这与字符串内任何地方的ASCII标点匹配,如果不匹配,则错误消息和相应的消息会弹出 -
.Matches("^[^£# “”]*$")
-匹配整个字符串,每个字符串的字符不能为£
,#
,空格,“
或”
。如果任何字符等于这些字符中的至少一个,则会弹出错误消息。
关于[][""!@$%^&*(){}:;<>,.?/+_=|'~\\-]
,]
是字符类中的第一个字符,不必进行转义。 -
放在字符类的末尾,也不必转义。