【问题标题】:Regular Expression Validation displaying error even when string is a match即使字符串匹配,正则表达式验证也会显示错误
【发布时间】:2014-01-03 14:49:51
【问题描述】:

问题如下,

当存在另一个验证消息时,我的视图上的正则表达式验证消息会显示,即使字符串与表达式匹配并且似乎它是由其他验证消息触发的,也会发生这种情况。

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 表达式 / val 消息有效,但如果确认字段不匹配,则显示两个验证消息。

Controler

    if (Regex.IsMatch(model.NewPassword, @"^(?=.{8})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)"))
            {
                if (model.NewPassword != model.NewPasswordConfim)
                {
                    return View("PasswordResetVerification", model);
                }
            }

在我的控制器中,我添加了一个检查以确保 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# regex asp.net-mvc validation data-annotations


【解决方案1】:

我认为您的正则表达式有问题,我检查了它是否正常工作.. 我试过了here

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

【讨论】:

  • 感谢您,我将正则表达式更改为以下^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{8,20}$'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多