Note that there are some explanatory texts on larger screens.

plurals
  1. POCompare (password) attribute
    text
    copied!<p>I'd like to create a view model for a new user using the code below. The "User" class contains just the two properties (simplified for now) that I will persist to the database; the view model adds a "compare password" field, which is only used in the view. I'd prefer to have the view model use the "User" class directly, rather than repeating all of the fields defined in "User".</p> <p>My question is how do I properly reference "User.Password" in the [Compare] attribute for the "ComparePassword" field?</p> <pre><code>public class User { [Required] public string UserName { get; set; } [Required] [DisplayName("Password")] [DataType(DataType.Password)] public string Password { get; set; } } public class NewUserViewModel { public User User { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("Re-enter Password")] [Compare("Password", ErrorMessage="Passwords must match")] public string ComparePassword { get; set; } } </code></pre> <p>The HTML that gets generated for "Password" and "ComparePassword" is below.</p> <pre><code>&lt;input class="text-box single-line password" data-val="true" data-val-required="The Password field is required." id="User_Password" name="User.Password" type="password" value="" /&gt; &lt;input class="text-box single-line password" data-val="true" data-val-equalto="Passwords must match" data-val-equalto-other="*.Password" data-val-required="The Re-enter Password field is required." id="ComparePassword" name="ComparePassword" type="password" value="" /&gt; </code></pre> <p>The key is how the "<strong>data-val-equalto-other</strong>" is handled by the Javascript. If I use "<strong>Password</strong>" or "<strong>User_Password</strong>" nothing happens - no check is performed. If I use "<strong>User.Password</strong>" the check is performed but always fails.</p> <p>I have no real problem doing this directly in jQuery, but would prefer to use the [Compare] attribute if at all possible.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload