Asp.net MVC verification of those things (4) -- custom verification features

Source: Internet
Author: User

In actual use of the project, the Validation Attribute provided by MVC by default is often insufficient to meet complex and variable verification requirements in reality. For example, in the process of registering a user, you often need to check the "disclaimer", this checkbox is often mandatory, but MVC does not provide the required verification for the checkbox. This article solves the checkbox mandatory verification problem to see how to define your own custom verification attributes in MVC. Reading Directory: 1. checkBox is required. implementation Analysis of server ValidationAttribute 3. enforceTrueAttribute can be customized for server-side verification. add client verification 5. conclusion 1: the dilemma of CheckBox mandatory verification first introduces the problem. below is the RegisterModel we have defined. to simplify the problem, only two attributes are defined. Copy the code public class RegisterModel {[DisplayName ("User Name")] [Required (ErrorMessage = "User Name is required")] public String UserName {get; set;} [Required] public bool IsAgreeTerm {get; set ;}} copy the code. We try to add the IsAgreeTerm to [Re Quired], hoping to help us implement required verification. The code for registering the View page is as follows: copy the code @ using (Html. beginForm () {@ Html. antiForgeryToken () @ Html. validationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @ Html. labelFor (m => m. employeeName) @ Html. editorFor (m => m. employeeName) <br/> @ Html. validationMessageFor (m => m. employeeName) </li> <li> @ Html. labelFor (m => m. isAgreeTerm) @ Html. editorFor (m => m. isAgreeTerm) <br/> @ Html. validationMessageFor (m => M. isAgreeTerm) </li> </ol> <input type = "submit" value = "Register"/> </fieldset>} copy the code and check the actual running effect: the User Name is required for verification, but the IsAgreeTerm is not prompted. This is because if the checkbox is not selected, the value submitted to the background is false. That is to say, the checkbox has a value no matter how it is. [Required] verifying Attribute cannot solve the verification problem for us as expected. Next we will implement our own ValidationAttribute to implement this verification. 2. Before performing the ValidationAttribute Implementation Analysis on the server, let's analyze the RequiredAttribute blog-requireattribute-code provided in MVC. We can see that RequiredAttribute inherits from the ValidationAttribute abstract class, the IsValid method is overwritten. that is to say, requiredattriid provides a method to determine whether the attribute of the RequiredAttribute verification rule is valid. In fact, the MVC server verification process is as follows: client request> Route parsing> model binding> data verification. now the idea should be clear, that is, inherit ValidationAttribute to implement our CheckboxRequiredAttribute. iii. Custom EnforceTrueAttribute implement server-side verification here we define an EnforceTrueAttribute to inherit ValidationAttribute copy code public class EnforceTrueAttribute: ValidationAttribute {public override bool IsValid (object value) {if (value = null) return false; if (value. getType ()! = Typeof (bool) throw new InvalidOperationException ("can only be used on boolean properties. "); return (bool) value;} public override string FormatErrorMessage (string name) {return" The "+ name +" field must be checked in order to continue. ";}} the copied code overwrites the two methods IsValid and FormatErrorMessage of the parent class. In the IsValid method, if the submitted checkbox value is not true, the verification fails. The FormatErrorMessage method displays error information based on the field name. enforceTrueAttribute applied on IsAgreeTerm. [DisplayName ("Term")] [EnforceTrue] public bool IsAgreeTerm {get; set;} compile and run, the effect after submitting the form is as follows: blog2-cnblogs.com 4, to add client verification, we not only want server verification, but also want to add client verification. 4.1 to implement token on EnforceTrueAttribute, you must first implement IClientValidatable on the server's EnforceTrueAttribute to copy the code public class EnforceTrueAttribute: ValidationAttribute, credential {public override bool IsValid (object value) {if (value = null) return false; if (value. getType ()! = Typeof (bool) throw new InvalidOperationException ("can only be used on boolean properties. "); return (bool) value;} public override string FormatErrorMessage (string name) {return" The "+ name +" field must be checked in order to continue. ";} public IEnumerable <ModelClientValidationRule> GetClientValidationRules (ModelMetadata metadata, ControllerContext context) {yield return new ModelClientV AlidationRule {ErrorMessage = String. IsNullOrEmpty (ErrorMessage )? FormatErrorMessage (metadata. displayName): ErrorMessage, ValidationType = "enforcetrue" };}in the code above, we have implemented the IClientValidatable interface method GetClientValidationRules, which returns ModelClientValidationRule, the information contained is ValidationType and ErrorMessage. by comparison, before and after EnforceTrueAttribute implements the IClientValidatable interface, the html difference in the previous section can be generated to understand the function of the modification method. blog-mvc-validation 4.2 extends the client verification method by implementing the IClientValidatable interface, we just applied the input of the label, and added There are additional verification rules, but there is no way to verify these rules on the client. The following describes how to extend the client verification framework unobtrusive to implement the complete client verification process. Copy the Code <script type = "text/javascript"> jQuery. validator. addMethod ("enforcetrue", function (value, element, param) {return element. checked;}); jQuery. validator. unobtrusive. adapters. addBool ("enforcetrue"); </script> copy Code 5. Here, the process to complete adding a custom verification is clear. 1. the server creates ValidationAttribute to inherit ValidationAttribute and implement server verification. validationAttribute inherits the client verification rules generated by the IClientValidatable interface. In addition, in actual development, the client extension verification method extends the verification rules to achieve data verification and achieve code reuse, it also makes data verification easier and more convenient.

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.