c# - 即使字符串匹配,正则表达式验证也会显示错误

标签 c# regex asp.net-mvc validation data-annotations

问题如下,

当存在另一条验证消息时,我的 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>

The result of a new password of qW345678 and a confirmation of qW3456789 (non mathcing)

最佳答案

我认为你的正则表达式有问题我检查过它不能正常工作.. 我试过了here

试试这个正则表达式 ^(?=.*\d)(?=.*[A-Z]).{8,20}$ 工作示例 here

关于c# - 即使字符串匹配,正则表达式验证也会显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906276/

相关文章:

c# - 将大量 ASCII 值(以字符串形式)转换为可读文本 C#

c# - 清理属性名称的字符串

c# - 如何匹配字符串中任意字符的偶数个?

python - 如何更改 re.sub 中的十进制数的十六进制数

asp.net - 访问类库中的 HttpContext - ASP.NET MVC

c# - MVC Razor View 中的 HTML.Textarea 值

c# - 升级到 5.0.0 后 TokenValidationParameters 不再起作用

c# - 意外的@using 关键字

javascript - 正则表达式:拆分字符

asp.net-mvc - UserManager.FindAsync 总是返回 null