EqualTo
The System.ComponentModel.DataAnnotations.CompareAttribute maps to the equalto validation method in jQuery Validation.
Here's the model, note that the Compare
attribute decorates the ConfirmEmail
property on the model:
using System.ComponentModel.DataAnnotations; namespace jQuery.Validation.Unobtrusive.Native.Demos.Models { public class EqualToModel { [Required, EmailAddress] public string EMail { get; set; } [Compare("EMail", ErrorMessage = "Emails do not match.")] public string ConfirmEmail { get; set; } } }
Here's the view (which uses the model):
@model jQuery.Validation.Unobtrusive.Native.Demos.Models.EmailModel @using (Html.BeginForm()) { <div class="row"> @Html.LabelFor(x => x.EMail, "An email address must be entered:") @Html.TextBoxFor(x => x.EMail, true) </div> <div class="row"> @Html.LabelFor(x => x.ConfirmEmail, "Please confirm your email address:") @Html.TextBoxFor(x => x.ConfirmEmail, true) </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-info">Reset</button> </div> }
Here's the HTML that the view generates:
<form action="/Demo/EqualTo" method="post"> <div class="row"> <label for="EMail">An email address must be entered:</label> <input data-msg-email="The EMail field is not a valid e-mail address." data-msg-required="The EMail field is required." data-rule-email="true" data-rule-required="true" id="EMail" name="EMail" type="text" value="an@emailaddress.com" /> </div> <div class="row"> <label for="ConfirmEmail">Please confirm your email address:</label> <input data-msg-equalto="Emails do not match." data-rule-equalto="#EMail" id="ConfirmEmail" name="ConfirmEmail" type="text" value="" /> </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-info">Reset</button> </div> </form>
Here's the JavaScript that initialises the validation:
$("form").validate({ submitHandler: function (form) { alert("This is a valid form!"); } });