Original: MVC validation 03-Custom validation rules, forbidden to enter certain values
This article continues to experience custom validation rules, where the requirement is to disallow the entry of certain values. This article is related to the first 2 articles, please refer to:
MVC authentication 01-BASIC, Remote authentication
MVC validation 02-Custom validation rules, message validation
Custom validation attributes inherit Validationattribute and implement the Iclientvalidatable interface
ExpandusingSystem.ComponentModel.DataAnnotations;usingSYSTEM.WEB.MVC;namespacemvcvalidation.extension{// <summary> /// used to disallow the input of a property value // </summary> Public Sealed classNoinputattribute:validationattribute, iclientvalidatable { Public stringInput {Get;Set; } PublicNoinputattribute (stringInput) { This. input = input; } Public Override BOOLIsValid (Object value) {//If no value is entered, release if(value==NULL) {return true; }if(value is string) {if(Input.contains (value. ToString ())) {return false; } }return true; } PublicSystem.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context) {Modelclientvalidationrule rule =Newmodelclientvalidationrule {ValidationType = "Noinput", errormessage = formaterrormessage (metadata. GetDisplayName ())}; Rule. Validationparameters["input"] = Input; YieldreturnRule } }}
To hit the properties of the view model with the custom attribute
Expand Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")] [Noinput ("Demo", errormessage ="This name cannot be used")] Public stringUserName {Get;Set; } [Required] [DataType (datatype.emailaddress)] [Display (Name = "Mail")] 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; } }
[Noinput ("demo", errormessage = "Cannot use this name")], that is, when the demo entered the error.
Extended jquery validation method jQuery.validator.noinput.js and register
The logic of jquery's validation extension method is essentially the same as the custom attribute IsValid () method.
Custom attribute rule. validationparameters["input"] key input to pass to the $.validator.unobtrusive.adapters.addsingleval () method.
ExpandThe//extended method name is consistent with Noinputattribute and is lowercase//value refers to the value of the front-end input//element refers to the HTML element//parm refers to the input parameters, that is, rule. validationparameters["input"] key input corresponding to the value, through the Noinputattribute constructor injection of the$.validator.addmethod ("Noinput", Function (value, element, param) {if(value==false) {//If value is not entered, release it here return true; }if(value. indexOf (param)! =-1) {//If the value of the front-end input contains the custom validation attribute Noinputattribute's attribute input value, it is not released return false; }Else{return true; }});///The first parameter is the jquery validation extension method name//The second parameter is rule. validationparameters[key for "input"]$.validator.unobtrusive.adapters.addsingleval ("Noinput", "input");
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 </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src="~/scripts/jquery.validator.noinput.js"></SCRIPT>}
Effect:
If you need to suppress more than one value, you need to override the custom validation attribute
This time the input property type of the custom attribute becomes string[], because multiple values are to be judged.
But the front desk rule. validationparameters["Input" should be stored as a string type, so the input array element is to be combined when saving.
ExpandusingSystem;usingSystem.ComponentModel.DataAnnotations;usingSYSTEM.WEB.MVC;namespacemvcvalidation.extension{// <summary> /// used to disallow the input of a property value // </summary> Public Sealed classNoinputattribute:validationattribute, iclientvalidatable { Public string[] Input {Get;Set; } PublicNoinputattribute (stringInput) {if(Input. IndexOf (",") >-1)//If the input string is comma delimited{//Assign a string to an array to input This. input = input. Split (New Char[] {', '}, stringsplitoptions.removeemptyentries); }Else{//without commas, construct an array to assign to input This. Input =New string[]{input}; } } Public Override BOOLIsValid (Object value) {//If no value is entered, release if(value==NULL) {return true; }if(value is string) {if(string. Join (",", Input). Contains (value. ToString ())) {return false; } }return true; } PublicSystem.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context) {Modelclientvalidationrule rule =Newmodelclientvalidationrule {ValidationType = "Noinput", errormessage = formaterrormessage (metadata. GetDisplayName ())}; Rule. Validationparameters["input"] =string. Join (",", Input); YieldreturnRule } }}
The custom attribute is hit on the property of the view model, but the constructor is a comma-delimited string
Expand Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")] [Noinput ("Demo,jack", errormessage ="This name cannot be used")] Public stringUserName {Get;Set; } [Required] [DataType (datatype.emailaddress)] [Display (Name = "Mail")] 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; } }
[Noinput ("Demo,jack", errormessage = "Cannot use this name")], will be an error when entering demo or Jack.
Extended jquery validation method jQuery.validator.noinput1.js and register
Need to put rule. validationparameters["Input"] stores the value of the split array, in traversal judgment.
ExpandThe//extended method name is consistent with Noinputattribute and is lowercase//value refers to the value of the front-end input//element refers to the HTML element//parm refers to the input parameters, that is, rule. validationparameters["input"] key input corresponding to the value, through the Noinputattribute constructor injection of the$.validator.addmethod ("Noinput", Function (value, element, param) {if(value==false) {//If value is not entered, release it here return true; } var validatestate =true;//param is the custom attribute rule. validationparameters["input"] corresponding valuevar Paramarr = Param.split (', ');//The first parameter is the index of the array element ///The second parameter is an array element$.each (Paramarr, function (index, ele) {if(value= = ele) {validatestate =false;return; } });returnValidatestate;});///The first parameter is the jquery validation extension method name//The second parameter is rule. validationparameters[key for "input"]$.validator.unobtrusive.adapters.addsingleval ("Noinput", "input");
REGISTER.CSHMTL To reference JQuery.validator.noinput1.js
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 </ol> <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script src="~/scripts/jquery.validator.noinput1.js"></SCRIPT>}
Effect: