[英]RegEx with fluent validation in C# - how to not allow spaces and certain special characters in a password?
到目前为止,这是我的 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("^[^£# “”]*$")
- 匹配整个字符串,每个字符不能是£
、 #
、空格、 “
或”
。 如果任何字符至少等于这些字符之一,则会弹出错误消息。 关于[][""!@$%^&*(){}:;<>,.?/+_=|'~\\\\-]
, ]
是字符类中的第一个字符,没有被逃避。 -
位于字符类的末尾,也不必转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.