在 C# 中进行流畅验证的 RegEx - 如何在密码中不允许空格和某些特殊字符?

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("^[^£# “”]*$") - 这匹配整个字符串,其中每个字符不能是 £#、space、.如果任何字符等于这些字符中的至少一个,则会弹出错误消息。

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