JS implementation policy Mode

Source: Internet
Author: User
Tags hasownproperty

Basic Concepts

The policy mode allows you to select an algorithm at runtime. The client of the code can work with the same interface. However, it selects an algorithm from multiple algorithms based on the context in which the customer is trying to execute the task.

One example of using the Policy mode is to solve the form verification problem. You can create a validator object with the validate () method. Regardless of the form type, this method is called and always returns the same result, an unverified data list, and any error message.

However, based on the specific form Form and data to be verified, the validator client can select different types of check methods. The validator selects the best policy to process the task, and entrust specific data verification to appropriate algorithms.

Data Verification example

Assume that the following data block may come from a form on the webpage, and you need to verify whether it is valid:

Var data = {
First_name: "Super ",
Last_name: "Man ",
Age: "unknown ",
Username: "o_0"
};
In this specific example, to enable the validator to know what is the best policy, you must first configure the validator and set rules that are considered valid and acceptable.

Validator. config = {
First_name: 'isnonempty ',
Age: 'isnumber ',
Username: 'isalphanum'
};
 
Validator. validate (data );
If (validator. hasErrors ()){
Console. log (validator. messages. join ("\ n "));
}
Then implement validator. First, implement the available algorithms used for inspection.

Validator. types. isNonEmpty = {
Validate: function (value ){
Return value! = '';
},
Instructions: "the value cannot be empty ."
};
 
Validator. types. isNumber = {
Validate: function (value ){
Return! IsNaN (value );
},
Instructions: "the value can only be a valid number, e.g. 1, 3.14 or 2010 ."
};
 
Validator. types. isAlphaNum = {
Validate: function (value ){
Return! /[^ A-z0-9]/I. test (value );
},
Instructions: "the value can only contain characters and numbers, no special symbols ."
};
Finally, the core validator object is as follows:

Var validator = {
// All available checks
Types :{},
 
// Error message in the current verification session
Messages: [],
 
// Name of the current verification configuration: verification type
Config :{},
 
// The interface method 'data' is a key-value pair.
Validate: function (data ){
Var I, msg, type, checker, result_ OK;
 
// Reset all information
This. messages = [];
 
For (I in data ){
If (data. hasOwnProperty (I )){
Type = this. config [I];
Checker = this. types [type];
 
If (! Type ){
Continue;
}
If (! Checker ){
Throw {
Name: "ValidationError ",
Message: "No handler to validate type" + type
};
}
 
Result_ OK = checker. validate (data [I]);
If (! Result_ OK ){
Msg = "Invalid value for *" + I + "*," + checker. instructions;
This. messages. push (msg );
}
}
}
Return this. hasErrors ();
},
 
// Help functions
HasErrors: function (){
Return this. messages. length! = 0;
}
};
Complete code:

Var validator = {
// All available checks
Types :{},
 
// Error message in the current verification session
Messages: [],
 
// Name of the current verification configuration: verification type
Config :{},
 
// The interface method 'data' is a key-value pair.
Validate: function (data ){
Var I, msg, type, checker, result_ OK;
 
// Reset all information
This. messages = [];
 
For (I in data ){
If (data. hasOwnProperty (I )){
Type = this. config [I];
Checker = this. types [type];
 
If (! Type ){
Continue;
}
If (! Checker ){
Throw {
Name: "ValidationError ",
Message: "No handler to validate type" + type
};
}
 
Result_ OK = checker. validate (data [I]);
If (! Result_ OK ){
Msg = "Invalid value for *" + I + "*," + checker. instructions;
This. messages. push (msg );
}
}
}
Return this. hasErrors ();
},
 
// Help functions
HasErrors: function (){
Return this. messages. length! = 0;
}
};
 
Validator. types. isNonEmpty = {
Validate: function (value ){
Return value! = '';
},
Instructions: "the value cannot be empty ."
};
 
Validator. types. isNumber = {
Validate: function (value ){
Return! IsNaN (value );
},
Instructions: "the value can only be a valid number, e.g. 1, 3.14 or 2010 ."
};
 
Validator. types. isAlphaNum = {
Validate: function (value ){
Return! /[^ A-z0-9]/I. test (value );
},
Instructions: "the value can only contain characters and numbers, no special symbols ."
};
 
Var data = {
First_name: "Super ",
Last_name: "Man ",
Age: "unknown ",
Username: "o_0"
};
 
Validator. config = {
First_name: 'isnonempty ',
Age: 'isnumber ',
Username: 'isalphanum'
};
 
Validator. validate (data );
If (validator. hasErrors ()){
Console. log (validator. messages. join ("\ n "));
}
The above validator object is generic, and the method to enhance the validator object is to add more type checks. If you use it on multiple pages, there will soon be a good set of specific checks. Therefore, for each new use case, you need to configure the validator and run validate () method.

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.