Compare password and confirm password in ASP.Net MVC

后端 未结 6 1045
遥遥无期
遥遥无期 2021-02-07 06:32

Is it possible to compare confirm password textbox\'s text with @Html.PasswordFor(model=>model.Password)?

@using (Html.BeginForm())
{
    

        
相关标签:
6条回答
  • 2021-02-07 06:42

    Using Compare DataAnnotation it will be easy to compare password but if model genrate from database use NotMapped, NotMapped Properties In An Entity Framework Using A Code-First Strategy

    [Required]
    public string Password { get; set; }
    
    [NotMapped] // Does not effect with your database
    [Compare("Password")]
    public string ConfirmPassword { get; set; }
    
    0 讨论(0)
  • 2021-02-07 06:42

    Just tried [Compare("field_to_compare")] and it also works in MVC 5.

    0 讨论(0)
  • 2021-02-07 06:49

    Try to write javascript for that to compare password...

    But DataAnnotation is Preferred

    0 讨论(0)
  • 2021-02-07 06:52

    Just add [NotMapped] to above of your Confirm password Property in Data Model

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

    By this way, it will not check ConfirmPassword property in your DB table

    0 讨论(0)
  • 2021-02-07 07:00

    change your model to include confirm password variable

    [Required]
    public string Password { get; set; }
    [Compare("Password")]
    public string ConfirmPassword { get; set; }
    
    0 讨论(0)
  • 2021-02-07 07:04

    It is possible to compare your "Password" text box value with a "Confirm Password" text box value both on client side and server side. The solutions given by others is for confirmation on server side. If you don't want to include "Confirm Password" in your model then you have to compare client side. This can be done through Javascript. Either you can manually write a code to compare or you can include the following script in your .cshtml file. (Assuming you are using Visual Studio to write your code).

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

    Then you should create a field like below:

     <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>
    

    This will compare your "Password" text box with "Confirm Password" text box and also show an error message if the values in both text box don't match, without you having to write any additional code.

    Although, a good practice is to do both client side as well as server side validation.

    0 讨论(0)
提交回复
热议问题