Shihan Khan
Shihan Khan

Reputation: 2188

Compare password using DataAnnotation in asp.net mvc

I'm trying to make a website using asp.net mvc 4 & EF6 where I've Password & Confirm Password fields. If both are same then data will be saved in MSSQL db as usual. I'm using Compare DataAnnotation to compare those two fields & I've added that code in EF6 generated model class. But for some reason, my data is not saving in db. Here are my codes,

Controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UserReg(ClientReg regCl)
    {
        if (ModelState.IsValid)
        {
            db.ClientRegs.Add(regCl);
            db.SaveChanges();
            return View();
        else
        {
            return RedirectToAction("Register");
        }
    }

Model

public partial class ClientReg
{
    public int serial { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    [Compare("password")]
    public string ComparePass { get; set; }
}

View

@model MyProj.Models.ClientReg
@using (Html.BeginForm("UserReg", "Home"))
{
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()

    <div class="editor-label">
        <strong>Username</strong>
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(a => a.username)
        @Html.ValidationMessageFor(a => a.username)
    </div>
    <div class="editor-label">
        <strong>Password</strong>
    </div>
    <div class="editor-field">
        @Html.PasswordFor(a => a.password)
        @Html.ValidationMessageFor(a => a.password)
    </div>
    <div class="editor-label">
        <strong>Confirm Password</strong>
    </div>
    <div class="editor-field">
        @Html.PasswordFor(a => a.ComparePass)
        @Html.ValidationMessageFor(a => a.ComparePass)
    </div>
    <input type="submit" value="Sign Up" />
}

I can't find any errors in my code. Am I doing something wrong here? How can I compare two password fields by using DataAnnotation? Need this help badly! Thanks.

Upvotes: 1

Views: 4368

Answers (1)

Vince Tino
Vince Tino

Reputation: 142

You should separate data access class from view model. The view model should contain the DataAnnotations.Compare attribute.

/* View model */
public partial class ClientRegModel
{
    public int serial { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    [Compare("password")]
    public string ComparePass { get; set; }
}

/* Your DbContext or data class */
public partial class ClientReg
{
    public int serial { get; set; }
    public string username { get; set; }
    public string password { get; set; }
}

You can also checkout this post How to properly implement "Confirm Password" in ASP.NET MVC 3?

Upvotes: 1

Related Questions