Original: MVC validation 05-Custom validation rules, validation of 2 attribute values
This article experiences a range of 2 attribute values. That is, when one property enters a value, the value entered by another property cannot be equal to the first property value. Related articles include:
MVC authentication 01-BASIC, Remote authentication
MVC validation 02-Custom validation rules, message validation
MVC validation 03-Custom validation rules, forbidden to enter certain values
MVC validation 04-Custom validation rules, date range validation
Custom validation attributes, inheriting Validationattribute and implementing iclientvalidatable
This time overrides another overload of the base class's IsValid () method, because the overload contains the validation context Validationcontext, from which you can get the properties and property values.
ExpandusingSystem.ComponentModel.DataAnnotations;usingSystem.Globalization;usingSYSTEM.WEB.MVC;namespacemvcvalidation.extension{ Public classnotequaltoattribute:validationattribute,iclientvalidatable { Public stringOtherproperty {Get;Set; } PublicNotequaltoattribute (stringOtherproperty) {otherproperty = Otherproperty; }protected OverrideValidationresult IsValid (Object value, Validationcontext Validationcontext) {//From the validation context to get the properties we wantvar property = ValidationContext.ObjectType.GetProperty (Otherproperty);if(Property = =NULL) {return NewValidationresult (string. Format (CultureInfo.CurrentCulture, "{0} does not exist", Otherproperty)); }//Gets the value of the propertyvar Othervalue = property. GetValue (Validationcontext.objectinstance,NULL);if(Object. Equals (value, Othervalue)) {return NewValidationresult (Formaterrormessage (validationcontext.displayname)); }return NULL; } PublicSystem.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context) {var rule =Newmodelclientvalidationrule {ValidationType = "Notequalto", errormessage = formaterrormessage (metadata. GetDisplayName ())}; Rule. Validationparameters[" Other"] = Otherproperty; YieldreturnRule } }}
View model
[Notequalto ("UserName", errormessage = "cannot be the same as the value of the user name")] is used to compare the value of the property UserName.
Expand Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")]//[remote ("Checkusername", "Validate", errormessage = "Remote Authentication user name failed")][Noinput ("Demo,jack", errormessage ="This name cannot be used")] Public stringUserName {Get;Set; } [Required] [DataType (datatype.emailaddress)] [Display (Name = "Mail")]//[email] Public stringEmail {Get;Set; } [Required] [stringlength (errormessage = "{ 0} field minimum {2} characters, up to {1} characters", Minimumlength = 6)] [DataType (Datatype.password)] [Display (Name ="Password")] Public stringPassword {Get;Set; } [DataType (Datatype.password)] [Display (Name = "Confirm Password")] [System.ComponentModel.DataAnnotations.Compare ("Password", errormessage ="The password and confirmation password do not match. ")] Public stringConfirmPassword {Get;Set; } [Notequalto ("UserName", errormessage ="cannot be the same as the value of the user name")] Public stringOthername {Get;Set; } }
Extending the validation of JQuery, JQuery.validator.noteaualto.js
JQuery.validator.addMethod (' noteaualto ', function (value, element, param) {
This means that the value of the form can be verified when it is empty
However, if the form has a value, it must meet | | After the condition, otherwise return false
return This value ! = $ (param). Val ();
});
The first parameter is a jquery validation extension method name
The second argument is with rule. validationparameters[key in "other"] corresponds
Option refers to an Modelclientvalidationrule object instance
JQuery.validator.unobtrusive.adapters.add (' Notequalto ', [' other '], function (options) {
options.rules[' Notequalto'# ' + options. params. Other;
if (options.message) {
options.messages[' Notequalto '] = options.message;
}
});
register.cshtml View
Expand@model mvcvalidation.models.registermodel@{viewbag.title = "Register";} class="title> using (Html.BeginForm ()) {@Html. AntiForgeryToken () @Html. ValidationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @Html. labelfor (M = m.username) @Html. Textboxfor (M + m.username) </li> <li> @Html. labelfor (M = m.email) @Html. textboxfor (M = m.email) </li> <li> @Html. labelfor (M = M. Password) @Html. passwordfor (M = m.password) </li> <li> @Html. labelfor (M = M.confirmpassword) @Html. passwordfor (M = m.confirmpassword) </li& Gt <li> @Html. labelfor (M = m.othername) @Html. textboxfor (M = m.othername) </li> </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src="~/scripts/jquery.validator.noteaualto.js"></SCRIPT>}
Effect: