在 MVC 中比较密码并确认密码 ASP.Net



是否可以将确认密码文本框的文本与 @Html.PasswordFor(model=>model.Password)

@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>@Html.LabelFor(model => model.Password)</td>
            <td>@Html.PasswordFor(model => model.Password)</td>
            <td>@Html.ValidationMessageFor(model => model.Password)</td>
        </tr>
        @*Here I want to take "Confirm Password" and want to compare it with "Password" in View(.cshtml only) as
          I have not taken ConfirmPassword in my model.*@
        <tr>
            <td>
                <input type="submit" value="Create" />
            </td>
        </tr>
    </table>              
}

请提出任何方式或解决方案,

如何在不获取模型中的确认密码属性的情况下compare passwordconfirm password。谢谢。。。。

使用Compare DataAnnotation将很容易比较密码,但如果模型从数据库生成,则使用NotMapped , 使用代码优先策略的实体框架中的 NotMapped 属性

[Required]
public string Password { get; set; }
[NotMapped] // Does not effect with your database
[Compare("Password")]
public string ConfirmPassword { get; set; }

更改模型以包含确认密码变量

[Required]
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPassword { get; set; }

只需在上面的数据模型中添加[NotMapped]确认密码属性

[NotMapped]
[Required(ErrorMessage = "Confirm Password required")]
[CompareAttribute("NewPassword", ErrorMessage = "Password doesn't match.")]        
public string ConfirmPassowrd { get; set; }

这样,它就不会检查数据库表中ConfirmPassword属性

刚刚尝试了[Compare("field_to_compare")],它也适用于 MVC 5。

尝试为此编写javascript以比较密码...

DataAnnotation是首选

可以将客户端和服务器端的"密码"文本框值与"确认密码"文本框值进行比较。其他人给出的解决方案是在服务器端进行确认。如果您不想在模型中包含"确认密码",则必须比较客户端。这可以通过Javascript完成。可以手动编写代码进行比较,也可以在 .cshtml 文件中包含以下脚本。(假设你正在使用Visual Studio来编写代码)。

<script src="/Scripts/jquery-3.3.1.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

然后,您应该创建一个如下所示的字段:

 <input  data-val="true" data-val-equalto="Password and Confirmation Password must match." data-val-equalto-other="*.Password" data-val-required="Required." id="ConfirmPassword" name ="ConfirmPassword"  type="password" />
<span class="field-validation-valid error" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true"></span>
这会将您的"密码"文本框

与"确认密码"文本框进行比较,如果两个文本框中的值不匹配,还会显示一条错误消息,而无需编写任何其他代码。

不过,一个好的做法是同时进行客户端和服务器端验证。

最新更新