C# 中具有流畅验证的正则表达式 - 如何不允许密码中出现空格和某些特殊字符?

ims*_*san 3 c# regex validation fluentvalidation

这是迄今为止我的 C# 应用程序中对密码的流畅验证

\n
RuleFor(request => request.Password)\n    .NotEmpty()\n    .MinimumLength(8)\n    .Matches("[A-Z]+").WithMessage("'{PropertyName}' must contain one or more capital letters.")\n    .Matches("[a-z]+").WithMessage("'{PropertyName}' must contain one or more lowercase letters.")\n    .Matches(@"(\\d)+").WithMessage("'{PropertyName}' must contain one or more digits.")\n    .Matches(@"[""!@$%^&*(){}:;<>,.?/+\\-_=|'[\\]~\\\\]").WithMessage("'{ PropertyName}' must contain one or more special characters.")\n    .Matches("(?!.*[\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d])").WithMessage("'{PropertyName}' must not contain the following characters \xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d or spaces.")\n    .Must(pass => !blacklistedWords.Any(word => pass.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0))\n        .WithMessage("'{PropertyName}' contains a word that is not allowed.");\n
Run Code Online (Sandbox Code Playgroud)\n

以下部分目前不起作用

\n
.Matches("(?!.*[\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d])").WithMessage("'{PropertyName}' must not contain the following characters \xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d or spaces.")\n
Run Code Online (Sandbox Code Playgroud)\n

例如,当密码为“Hello12!#”时,不会返回验证错误。\n\xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d 密码中不应允许存在空格,并且如果其中有任何一个如果存在,验证应失败,并显示“{PropertyName}”不得包含以下字符 \xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d 或空格。错误信息。

\n

如何修改它以使其正常工作?

\n

Wik*_*żew 5

您可以使用

\n
RuleFor(request => request.Password)\n    .NotEmpty()\n    .MinimumLength(8)\n    .Matches("[A-Z]").WithMessage("\'{PropertyName}\' must contain one or more capital letters.")\n    .Matches("[a-z]").WithMessage("\'{PropertyName}\' must contain one or more lowercase letters.")\n    .Matches(@"\\d").WithMessage("\'{PropertyName}\' must contain one or more digits.")\n    .Matches(@"[][""!@$%^&*(){}:;<>,.?/+_=|\'~\\\\-]").WithMessage("\'{ PropertyName}\' must contain one or more special characters.")\n    .Matches("^[^\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d]*$").WithMessage("\'{PropertyName}\' must not contain the following characters \xc2\xa3 # \xe2\x80\x9c\xe2\x80\x9d or spaces.")\n    .Must(pass => !blacklistedWords.Any(word => pass.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0))\n        .WithMessage("\'{PropertyName}\' contains a word that is not allowed.");\n
Run Code Online (Sandbox Code Playgroud)\n

笔记:

\n
    \n
  • .Matches(@"[][""!@$%^&*(){}:;<>,.?/+_=|\'~\\\\-]")- 这与字符串内任何位置的 ASCII 标点符号相匹配,如果没有,则会弹出错误并显示相应的消息
  • \n
  • .Matches("^[^\xc2\xa3# \xe2\x80\x9c\xe2\x80\x9d]*$")- 这匹配整个字符串,其中每个字符不能是\xc2\xa3#、 空格\xe2\x80\x9c\xe2\x80\x9d。如果任何字符至少等于这些字符之一,则会弹出错误消息。
  • \n
\n

对于[][""!@$%^&*(){}:;<>,.?/+_=|\'~\\\\-]]是字符类中的第一个字符,不必是转义字符。放置-在字符类的末尾,也不必转义。

\n