ASP. NET MVC validation-custom validation rules, validation of 2 attribute values not equal to "pending verification"

Source: Internet
Author: User

Tip: Do not prompt for error messages after saving

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.

Using system.componentmodel.dataannotations;using system.globalization;using System.web.mvc;namespace mvcvalidation.extension{public class Notequaltoattribute:validationattribute,iclientvalidatable {public S        Tring Otherproperty {get; set;}        Public Notequaltoattribute (String otherproperty) {otherproperty = Otherproperty;            } protected override Validationresult IsValid (object value, Validationcontext validationcontext) {            From the validation context we can get the properties we want var property = ValidationContext.ObjectType.GetProperty (Otherproperty); if (property = = null) {return new Validationresult (string.            Format (CultureInfo.CurrentCulture, "{0} does not exist", otherproperty)); }//Gets the value of the attribute var Othervalue = property.            GetValue (validationcontext.objectinstance, NULL); if (object. Equals (value, Othervalue)) {return new Validationresult (formaterrormessAge (Validationcontext.displayname));        } return null; } Public system.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (            Modelmetadata metadata, ControllerContext context) {var rule = new Modelclientvalidationrule {ValidationType = "Notequalto", errormessage = formaterrormessage (metadata.            GetDisplayName ())}; Rule.            Validationparameters["other"] = Otherproperty;        yield return rule; }    }}

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.

 public class Registermodel {[Required] [Stringlength (6, minimumlength = 2)]//Add [Display (Name =  "User name")]//[remote ("Checkusername", "Validate", errormessage = "Remote Authentication user name failed")] [Noinput ("Demo,jack", errormessage        = "Cannot use this name")] public string UserName {get; set;}        [Required]        [DataType (Datatype.emailaddress)]        [Display (Name = "mail")]//[email] public string Email {get; set;}        [Required]        [Stringlength (errormessage = "{0} field min {2} characters, up to {1} words", minimumlength = 6)]        [DataType (Datatype.password)]        [Display (Name = "password")] public string Password {get; set;}        [DataType (Datatype.password)]        [Display (Name = "Confirm password")] [System.ComponentModel.DataAnnotations.Compare ("Password", errormessage = "Password and Confirm password do not match. ")] public string ConfirmPassword {get; Set    } [Notequalto ("UserName", errormessage = "cannot have the same value as the user name")] public string Othername {get; set;} }

Extending the validation of JQuery, JQuery.validator.noteaualto.js

JQuery.validator.addMethod (' Notequalto ', 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
    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[' # ' + options.  Params.other; 
    if (options.message) {
        options.messages[' notequalto '] = options.message;
    }
});   

register.cshtml View

@model mvcvalidation.models.registermodel@{viewbag.title = "register";} 

Effect:

Transferred from: http://www.csharpwin.com/dotnetspace/13573r4911.shtml

ASP. NET MVC validation-custom validation rules, validation of 2 attribute values not equal to "pending verification"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.