[英]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.