In the previous articleArticleYou have introduced the use of various built-in validators (first-class validators) in the validation module. Today we will continue with the following two types of validators:Independent validatorsAndCustomize the validators and supplement the configuration classes of the validators in the validation module.
1. independent validators
In my previous article, I classified andcompositevalidator and orcompositevalidator as independent validators. These two validators primarily serve the first type of authentication service and can be combined for complex verification:
Andcompositevalidator-combination verification, logic and verification. If all the various verifications are passed
Orcompositevalidator-combination verification, logic or verification. If one of the multiple verifications is passed
The two validators can be configured through the configuration tool:
The configuration method is the same as the original configuration, except that the specific validators are placed in andcompositevalidator or orcompositevalidator.
You can also writeCodeTo create:
Validator v = new andcompositevalidator (New notnullvalidator (), new stringlengthvalidator (1, 16); V. Validate (name4 );
In this way, the two validators are packaged together to verify the name4 attribute.
(Note: All validators In the first type inherit from validator, so you can write code for verification in addition to features and configurations.)
Ii. Custom Verification
When we find that the built-in validators of the validation module are insufficient for our daily needs during project development, we need to expand and establish custom Verification Based on our own needs.
The extended interface has been provided for us under the validation module (for details about the implementation level of the validation module, refer to "Part 1 ",The validators must inherit from the validator class.)
To implement a custom interface, consider the following steps:
1. Customize the verification method of the validators
Considering the authentication method of the User-Defined validators, are you sure you want to verify the method of your user-defined validators only for feature verification, or for the configurator verification or for both?
2. Start Encoding
After confirming the verification method, you can start to write a specific validator, let's take a look at how to compile the validators that implement different authentication methods (I will directly reference the three examples in the hol provided by the Microsoft Enterprise Library for 9-11)
Before implementing various verification methods, you must first create a specific validators, such as stringlengthvalidator. Because I am referring to Hol, I will directly reference ssnvalidator. CS:
Using system; using system. text. regularexpressions; using Microsoft. practices. enterpriselibrary. validation; using Microsoft. practices. enterpriselibrary. validation. validators; namespace validationhol. customvalidators {public class ssnvalidator: validator <string> {public ssnvalidator (string tag): This (TAG, false) {} public ssnvalidator (string tag, bool ignorehypens): Base (string. empty, tag) {This. I Gnorehypens = ignorehypens;} static RegEx ssncaptureregex = new RegEx (@ "^ (? <Area> \ D {3 })-(? <Group> \ D {2 })-(? <Serial> \ D {4}) $ "); static RegEx ssncapturenohypensregex = new RegEx (@" ^ (? <Area> \ D {3 })(? <Group> \ D {2 })(? <Serial> \ D {4}) $ "); Private bool ignorehypens; protected override string defamessmessagetemplate {get {Throw new partition () ;}} protected override void dovalidate (string objecttovalidate, object currenttarget, string key, validationresults) {match = (ignorehypens? Ssncapturenohypensregex: ssncaptureregex ). match (objecttovalidate); If (match. success) {string area = match. groups ["area"]. value; string group = match. groups ["group"]. value; string serial = match. groups ["serial"]. value; If (Area = "666" | string. compare (area, "772", stringcomparison. ordinal)> 0) {logvalidationresult (validationresults, "invalid Area", currenttarget, key);} else if (Area = "000" | group = "00" | serial = "0000") {logvalidationresult (validationresults, "SSN elements cannot be all '0'", currenttarget, key) ;}} else {logvalidationresult (validationresults, this. ignorehypens? "Must be 9 digits": "must match the pattern '#########'", currenttarget, key );}}}}
It can be seen that this validators class is relatively simple. This class is mainly used to verify the format correctness of the American Social Security number. This class inherits from the generic abstract class.Validator <string>, Implements the following functions:
1)Defaultmessagetemplate, Returns an exceptionNotimplementedexceptionHere we don't have to worry about it.
2)Implemented the dovalidate method.This is an important point. It was also mentioned in the previous article that this method is mainly used for specific verification, it can be seen from the method that its essence is to verify the social security number through the regular expression (I will not introduce the verification rules, you can search for them if you are interested), if the verification fails, it will passMethod logvalidationresultTo record messages and results.
3)ConstructorThis verification has two constructor. The constructor receives two parameters. One parameter is the verification tag (which stores some verification information ), another parameter, ignorehypens, indicates whether to ignore the hyphen during verification.
After implementing the main business logic validators, we can start to write the corresponding classes based on the authentication method:
1) method Verification
If this verification method is used, you do not need to write any code. You can directly instantiate the ssnvalidator and call the method dovalidate for verification.
2) feature Verification
For this verification method, you need to write a feature class. We can refer to the format of the validator built in the validation module, named ssnvalidatorattribute, and see the following code:
Using system; using Microsoft. practices. enterpriselibrary. validation; using Microsoft. practices. enterpriselibrary. validation. validators; namespace validationhol. customvalidators {public class ssnvalidatorattribute: validatorattribute {protected override validator docreatevalidator (type targettype) {return New ssnvalidator (this. tag );}}}
This feature class is also very simple, that is, inheriting the Abstract Feature class validatorattribute,Reload implementation method docreatevalidator creates the validators ssnvalidator for verification.
In this way, you only need:
[Ssnvalidator] Public String SSN {Get; set ;}
3) configurator Verification
For better and more convenient validators, we can allow ourselves to write and verify the configuration through the configurator. In this case, we need to add an ssnvalidatordata class, this class is used to connect to the configuration tool of the enterprise database. Let's look at the specific code:
Using system; using system. configuration; using Microsoft. practices. enterpriselibrary. validation; using Microsoft. practices. enterpriselibrary. validation. configuration; using Microsoft. practices. enterpriselibrary. common. configuration. design; using validationhol. customvalidators. properties; namespace validationhol. customvalidators. configuration {[resourcedescription (typeof (resources), "ssnvalidatordescription")] [resourcedisplayname (typeof (resources), "ssnvalidatorname")] public class ssnvalidatordata: valuevalidatordata {public partition () {} public ssnvalidatordata (string name): Base (name, typeof (ssnvalidator) {} [configurationproperty ("ignorehyphens")] [resourcedescription (typeof (resources ), "ignorehyphensdescription")] [resourcedisplayname (typeof (resources), "ignorehyphensname")] public bool ignorehyphens {get {return (bool) This ["ignorehyphens"];} set {This ["ignorehyphens"] = value ;}} protected override validator docreatevalidator (type targettype) {return New ssnvalidator (this. tag, this. ignorehyphens );}}}
This configuration class has the following three points of attention:
1) If you want to add comments to the configured validators When configuring the configuration tool of the enterprise database, you need to put the comments into the resource file like the authentication message, at the same time, add features on the class and corresponding attributes to get comments, such as [resourcedescription (typeof (resources), "ssnvalidatordescription")], [resourcedisplayname (typeof (resources ), "ssnvalidatorname")]
2) You can add properties in the configurator to obtain information from the enterprise database configuration tool.
3) The configuration class must inherit the abstract class valuevalidatordata directly or indirectly, and the implementation method docreatevalidator is used to create the validator instance for verification.
After writing the configuration class, we also need to add a feature for the validator class to identify the Configuration:
[Configurationelementtype (typeof (ssnvalidatordata)] public class ssnvalidator
After re-compilation, We can configure it through the configurator. we can add a customvalidator in the enterprise database configuration tool, and then select the ssnvalidator we wrote:
Iii. omitted supplement: A Brief Introduction to the configuration classes of validators in the validation module
In the previous article, I introduced the inheritance levels and attributes of the validators and feature classes, but missed the configuration information of the validators, first, let's take a look at the specific structure (here I still put two types of validators configuration classes, one is the type conversion validators and the other is the string length validators ):
From this figure, we can clearly understand the inheritance level of the configuration class of the validators of the validation module:
Ivalidatordescriptor-> validatordata-> valuevalidatordata-> Configuration class of the validator
Interface ivalidatordescriptor
The createvalidator method is provided. You can create verification classes based on your needs, and the enterprise database configurator can obtain the specific verification classes configured.
Abstract class validatordata
The implementation interface ivalidatordescriptor is similar to the combination of the validation feature class basevalidationattribute and validatorattribute. It abstracts the methods for creating the validators, verification messages, and verification results:
1) Verify the message template with the messagetemplate attribute
2) attributes: messagetemplateresourcename, messagetemplateresourcetypename, Resource Name of the message template, and Resource Type
3) attribute tag, which stores verification results
4) the virtual method docreatevalidator is used to overwrite the quilt class and create a specific validators.
5) The ivalidatordescriptor. createvalidator method is used to create the validators for the ivalidatordescriptor interface. It internally calls the virtual method docreatevalidator to obtain the specific validators.
6) getmessagetemplate and getmessagetemplateresourcetype Methods: get the message template and get the message template based on the resource type.
Abstract class valuevalidatordata
A negative logic attribute is encapsulated. Its function is similar to the valuevalidatorattribute verification feature class, but isvalid and formaterrormessage methods are less than valuevalidatorattribute.
Configuration class of validators
This class is created based on the specific business logic. The implementation method validator docreatevalidator (type targettype) reads the verified object based on the configuration information, and then creates a specific validator for verification.
Abstract generic rangevalidatordata <t>
There is also a class rangevalidatordata <t>, which is different from the general business logic validator configuration class, which provides abstraction for all the validator configuration classes that require range Verification:
1) Generic attributes lowerbound and upperbound, with the upper limit and lower limit
2) The enumerated property lowerboundtype and upperboundtype indicate the range boundary.
3) The generic t of this class must be able to implement icomparable <t>
(Note: If you need to add comments to all attributes of the configuration class, you can easily display the annotations in the Enterprise Library Configuration tool and put them in the resource file like the authentication message, at the same time, add features on the class and corresponding attributes to get comments, such as [resourcedescription (typeof (resources), "ssnvalidatordescription")], [resourcedisplayname (typeof (resources ), "ssnvalidatorname")])
So far, the enterprise database validation module information, the implementation level of the validators, and the usage methods of various validators are all from the enterprise database.Source codeAnd my personal understanding. If you have any mistakes in this article, please point out.
In the next article, I will continue with the introduction of the enterprise database validation module, which mainly introduces some simple applications of the validation module in the learning path project and the simple analysis of the Asp.net control provided by the enterprise database validation module.
Index of a series of articles on the learning path of Microsoft enterprise database 5.0:
Step 1: getting started
Step 2: Use the vs2010 + data access module to create a multi-database project
Step 3: Add exception handling to the project (record to the database using custom extension)
Step 4: Use the cache to improve the website's performance (entlib caching)
Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1
Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1
Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 2
Step 6: Use the validation module for server-side data verification
Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 1
Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 2
Step 8. Use the configuration setting module and other methods to classify and manage enterprise database configuration information
Step 9: Use the policyinjection module for AOP-PART1-basic usage
Step 9: Use the policyinjection module for AOP-PART2-custom matching rule
Step 9: Use the policyinjection module for AOP-PART3 -- Introduction to built-in call Handler
Step 9: Use the policyinjection module for AOP-PART4 -- create a custom call handler to achieve user operation Logging
Step 10: Use unity to decouple your system-Part1-Why use unity?
Step 10: Use unity to decouple your system-Part2-learn how to use Unity (1)
Step 10. Use unity to decouple your system-Part2-learn how to use Unity (2)
Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)
Step 10: Use unity to decouple your system-Part3-dependency Injection
Step 10: Use unity to decouple your system-part4 -- unity & piab
Extended learning:
Extended learning and dependency injection in libraries (rebuilding Microsoft Enterprise Library) [go]