The strategy pattern defines the algorithm family, which is packaged so that they can be replaced by each other, and this pattern allows the algorithm to change independently from the customer who uses the rice.
First, define a simple input form:
This kind of writing function can certainly meet the requirements, but, there will be several problems:
1. If I want to use on other pages, it is necessary to copy the code, the so-called reuse becomes a duplication, the code will have a lot of duplication. A little better. The check code will be sorted and encapsulated, and there will be more duplicate copies.
2. If I want to add an input validation, then directly modify the Submit function, the function will be significantly bloated, and is to destroy the "open and close" principle.
3. If you modify the Submit function, you must cover the test of the function design, because you do not know when the error will occur or unknown.
Transformation steps:
1. Each validation logic is considered a validation strategy and encapsulated into each validation policy function, the function parameters are consistent, you can accept DOM elements, validated values, error messages, custom parameters.
2. Define the validator, you can import the validation policy functions, or you can add them.
3. The validator provides a validation method for the call when validating, and its internal invocation of the specific validation policy function.
4. Verify the call.
Step 1.
Each of the if is treated as a validation business rule, with each business rule as a separate policy function, encapsulating all policy functions into a policy object.
var validationstrategies = {
isnoempty:function (element, errmsg, value) {
if (value = = ") {return
This.bui Ldinvalidobj (element, errmsg, value);
}
,
minlength:function (element, errmsg, value, length) {
if ( Value.length < length) {return
this.buildinvalidobj (element, errmsg, value);
}
,
maxLength: function (element, errmsg, value, length) {
if (value.length > Length) {return
this.buildinvalidobj ( Element, errmsg, value);
}
,
ismail:function (element, errmsg, value, length) {
var reg =/^ (\w-*\. *) +@ (\w-?) + (\.\w{2,}) +$/;
if (!reg.test (value)) {return
this.buildinvalidobj (element, errmsg, value);
}
}
;
The first 3 of the parameters of all functions are consistent, and are required to represent the validated DOM elements, error messages, validated values, and the 4th begins with the validation rules of the function itself to determine the custom parameters, which can have multiple parameters.
The "Buildinvalidobj" method simply returns the first 3 arguments to an Error object, and returns the Error object if the validation does not pass.
Depending on the dependency inversion principle, high-level modules should not be dependent on low-level modules and therefore cannot be used directly by the authenticating caller.
Encapsulation and abstraction by way of validator.
Step 2:
Define validators, you can import all of the validation policies, or you can add validation policy functions separately.
Input validator
function inputvalidators () {
this.validators = [];
This.strategies = {};
}
Import validation Policy functions
//Parameters from policy objects:
//Strategies: objects containing various policy functions
InputValidators.prototype.importStrategies = function (Strategies) {
for (var strategyname in strategies) {
this.addvalidationstrategy (strategyname, Strategies[strategyname) );
}
};
Add validation policy function
//parameter:
//Name: Policy name
//strategy: Policy function
InputValidators.prototype.addValidationStrategy = function (name, strategy) {
this.strategies[name] = strategy;
};
Step 3:
Add validation methods to accept external calls.
The first parameter rule, set to validation rules, such as "Minlength:6", generates a call to a specific policy function by using the following code, which is pressed into the cache, waiting to be invoked together.
": 6" indicates the parameters that the policy function customizes according to its own rules.
Add authentication method
//parameter:
//rule: Validation policy string
//element: Validated DOM element//
errmsg: Message displayed when validation fails
//value: Validated value
InputValidators.prototype.addValidator = function (rule, element, errmsg, value) {
var so = this;
var ruleelements = Rule.split (":");
This.validators.push (function () {
var strategy = Ruleelements.shift ();
var params = ruleelements;
Params.unshift (value);
Params.unshift (errmsg);
Params.unshift (element);
Return that.strategies[strategy].apply (that, params);
});
All validation is invoked with a check function. and returns the result of the error.
Start validation
InputValidators.prototype.check = function () {
for (var i = 0, validator validator = this.validators[i++] ;) {
var result = validator ();
if (result) {return result
}}
;
Step 4:
In the place where validation is needed, a new validator object is first.
var validators = new Inputvalidators ();
Import the object that contains the validation policy function, or add the validation policy function separately.
Validators.importstrategies (validationstrategies);
Validators.addvalidationstrategy (' IsEqual ', function (element, errmsg, value1, value2) {
if (value1!==) { return
this.buildinvalidobj (element, errmsg, value1);
}
);
As can be seen, different validation strategies can be encapsulated in the policy object, or can be added immediately according to the actual situation.
The validation method is then added to the validator with the validation policy, the validated DOM element, the error message, and the validated value, thus avoiding the direct invocation of the policy object and reducing the coupling.
var eleusername = document.getElementById (' UserName ');
Validators.addvalidator (' Isnoempty ', eleusername, ' username cannot be empty ', eleusername.value);
Validators.addvalidator (' Minlength:6 ', Eleusername, ' username number must be 6 to 20 characters ', eleusername.value);
Validators.addvalidator (' maxlength:20 ', Eleusername, ' username number must be 6 to 20 characters ', eleusername.value);
var Elepassword = document.getElementById (' password ');
Validators.addvalidator (' Isnoempty ', Elepassword, ' password cannot be empty ', elepassword.value);
Validators.addvalidator (' Minlength:6 ', Elepassword, ' the number of characters of the password must be 6 to 20 ', elepassword.value);
Validators.addvalidator (' maxlength:20 ', Elepassword, ' the number of characters of the password must be 6 to 20 ', elepassword.value);
var Elerepassword = document.getElementById (' Repassword ');
Validators.addvalidator (' Isnoempty ', Elerepassword, ' Confirm password cannot be empty ', elerepassword.value);
Validators.addvalidator (' Minlength:6 ', Elerepassword, ' the number of characters to confirm password must be 6 to 20 ', elerepassword.value);
Validators.addvalidator (' maxlength:20 ', Elerepassword, ' the number of characters to confirm password must be 6 to 20 ', elerepassword.value); Validators.addvalidaTor (' isequal: ' + elepassword.value, Elerepassword, ' two times password inconsistent ', elerepassword.value);
var elemail = document.getElementById (' mail ');
Validators.addvalidator (' Isnoempty ', Elemail, ' mailbox cannot be empty ', elemail.value); Validators.addvalidator (' IsMail ', Elemail, ' mailbox is not a valid format ', elemail.value);
Call the validator's check to perform all validation.
var result = Validators.check ();
if (result) {
alert (result.errmsg);
Result.element.focus ();
Result.element.select ();
return false;
}
Check returns the Error object, which we can then use to uniformly prompt the DOM elements, such as setting the focus, selecting the contents, or wrapping a red layer on the outside of the input box.
At this point, you can see through the change in the policy model, input validation, we only need to care about which validation rules, what kind of informational information, no longer exposed implementation details, easy to invoke, convenient for subsequent expansion and component.
All code:
The above is a small set to introduce the JavaScript design pattern-the policy mode of input validation of all the content, I hope you like.