问题如下,
当存在另一条验证消息时,我的 View 中会显示正则表达式验证消息,即使字符串与表达式匹配并且看起来像是被其他验证消息触发时也会发生这种情况。
View
[Required]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.{8})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)", ErrorMessage = "message")]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("NewPassword")]
[Display(Name = "Confirmation Password")]
public string NewPasswordConfim { get; set; }
在上面的模型中,我有我的正则表达式,它应该强制使用 1 个小写字母、1 个大写字母和 1 个数字字符的密码,另一个验证是将密码确认与新密码字段进行比较。
reg expression/val 消息在字符串有效或确认字段与新密码字段匹配时起作用,但如果确认字段不匹配,则会显示两个验证消息。
Controler
if (Regex.IsMatch(model.NewPassword, @"^(?=.{8})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)"))
{
if (model.NewPassword != model.NewPasswordConfim)
{
return View("PasswordResetVerification", model);
}
}
在我的 Controller 中,我添加了一个检查以确保 reg 表达式有效(作为测试)并且此检查在字符串与表达式匹配但确认密码字段与新密码字段reg表达式错误信息仍然显示错误。
View
<div class="form-group">
<label class="col-md-2 control-label" for="NewPassword">New Password</label>
<div class="col-md-4">
<input type="password" class="form-control" id="NewPassword" name="NewPassword" placeholder="Password" value="@Model.NewPassword" />
@Html.ValidationMessageFor(m => m.NewPassword)
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="NewPasswordConfim">Confim New Password</label>
<div class="col-md-4">
<input type="password" class="form-control" id="NewPasswordConfim" name="NewPasswordConfim" placeholder="Confim Password" value="@Model.NewPasswordConfim" />
@Html.ValidationMessageFor(m => m.NewPasswordConfim)
</div>
</div>
最佳答案
关于c# - 即使字符串匹配,正则表达式验证也会显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906276/