JavaScript I know-design pattern (bridging) applications-validators

Source: Internet
Author: User

 

 

Introduction:

First of all, please come with me to review the Bridge Mode in the design mode. There is not much nonsense:

 

In this design pattern, our abstract classes and implementation classes can be expanded and encapsulated separately so that they can be decoupled and many changes can be produced through combination. This idea also conforms to the design principle of "less inheritance and more combination. in the bridge mode, we can use the aggregate action class to bridge the ConreteImplementor and the refinedized aggregate action. But how does JavaScript implement bridging? Please follow me

1 // Validation class:

2

3

4 Validation = {

5 required: function (elem ){

6 return! $ (Elem). val (). trim (). isNullOrEmpty ();

7 },

8 email: function (elem ){

9 returnValidation. regexValidator ($ (elem). val (). trim (), Validation. Regex. email );

10 },

11 regexValidator: function (elemVal,/* string */regex ,){

12 if (! ElemVal. isNullOrEmpty ()&&! (ElemVal. match (regex, "\ g "))){

13 returnfalse;

14} else {

15 returntrue;

16 };

17 },

18 Regex :{

19 email:/^ \ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w + )? $/

20}

21 };

22 Validation. validateColl = {

23 'jq-validation-required': {validFunc: Validation. required, ErrMsg: 'required '},

24 'jq-validation-email ': {validFunc: Validation. email, ErrMsg: 'invalid email address '}

25 };

26 Validator class:

27

28

29 (function (){

30 varvalidator_elements_blur_selector = 'input [type = "text"] ';

31 varvalidator_elements_change_selector = 'select, input [type = "hidden"] ';

32 var validator_elements_selector = validator_elements_blur_selector + ',' + validator_elements_change_selector;

33

34 Validator = function (validateScopeSelector ){

35 this. _ validateColl = $. extend (true, {}, Validation. _ validateColl );

36 this. _ validateDom =$ (validateScopeSelector );

37 vartheValidator = this;

38 this. _ validateDom. delegate (validator_elements_blur_selector, 'blur', function (){

39 theValidator. validateInput (this, 'blur ');

40 });

41 this. _ validateDom. delegate (validator_elements_change_selector, 'change', function (){

42 varinputValidated = theValidator. validateInput (this, 'change ');

43 });

44 };

45

46 Validator. prototype = {

47 validate: function (){

48 varvalidated = true;

49 vartheValidator = this;

50 $ (validator_elements_selector, this. _ validateDom). each (function (){

51 if (! TheValidator. validateInput. call (theValidator, this )){

52 validated = false;

53 };

54 });

55 returnvalidated;

56 },

57 validateInput: function (elem, event ){

58 varinput = $ (elem );

59 varclassArr = input. attr ('class'). split ('');

60

61 varvalidated = true;

62 varinValidTable = new Hashtable ();

63 for (var I = 0; I <classArr. length; I ++ ){

64 varclassItem = classArr [I];

65 if (! ClassItem. startWith ('jq-validation ') continue;

66 varvalidateItem = this. _ validateColl [classItem];

67 if (validateItem & validateItem. validFunc ){

68 if (! ValidateItem. validFunc (input, validateItem )){

69 validated = false;

70 if (! StrPopupErr. isNullOrEmpty ()){

71 strPopupErr + = "";

72}

73 inValidTable. add (classItem, validateItem );

74}

75}

76}

77 returnvalidated;

78}

79 };

80 })();

81 // call example:

82

83 <div id = "validation_region">

84 <input type = "text" class = "jq-validation-required"/>

85 <input type = "text" class = "jq-validation-email"/>

86 </div>

87 <input type = "button" onclick = "submit ()"/>

88

89 <script language = "javascript" type = "text/javascript">

90 var validator = new Validator ("# validation_region ");

91 function submit (){

92 if (validator. validate ()){

93 alert ('verification passed! ');

94} else {

95 alert ('verification failed! ');

96}

97}

98 </script>

99

 

Explanation:

1. Design Philosophy

Among them, Validation can define and extend the methods of various verification rules, while Validator is responsible for handling error prompts after verification and correct feedback to the Code caller for verification. validateColl defines which type of verification calls the processing method of which verification rule, and their respective division of labor is clear, which also conforms to the design principle of single responsibility. In the above code, we can see that the Validation object is the implementation class, while the Validator object is the corrected abstract class, while the Validation. validateColl is the bridge (this definition is not available in the classic Gof 23 mode ). Of course, the above Code cannot be fully described here according to the terms defined in the design pattern. We only design and construct our code according to the ideas and concepts of the design model.

2. Working Principle

In the call example:

Var validator = newValidator ("# validation_region ");

 

After the page is loaded, we first instantiate the Validator object and pass in the Scope to be verified. Here we pass in the ID of the region to be verified, we use jQuery's $ () method to convert the selector "# validation_region" to an operational DOM object.

When the Button is clicked, the submit method is called. Then, validator is executed. the validate method. This method uses jQuery's each method to traverse all input controls within the verification range for verification, and finally returns the verification result.

In the internal method of Validate, we can also add the function of changing the style of input and error prompt when verification is not passed. The general method is to add a red border to the input to prompt the user, here, this function requires the reader to expand according to the project's needs.

 

3. extended verification rules

We have explained the design concept and working principle above. How can we expand validation?

We only need to add a new verification Rule Method to the Validation object, and bridge the verification type (input class name) and the new Validation rule in Validation. validateColl.

For example:

If we want to add a rule to verify whether it is a number, we need to add

Number: function (elem ){

Return! IsNaN ($ (elem). val ());

}

And add it to Validation. validateColl.

'Jq-validation-number': {validFunc: Validation. number, ErrMsg: 'notnumber '}

In this case, you do not need to change any Validator code. You can add 'jq-validation-number' to the input class for digit rule verification.

Here we need to note that if you need to perform multiple verification rules for an input, you can write the names of multiple verification rules in the class separated by spaces.

For example:

<Input type = "text" class = "jq-validation-requiredjq-validation-number"/>

Note: The image is taken from the design model series of Lu Zhenyu in the blog Park. You can refer to the reference address to learn more about the Bridge Mode:

Http://www.cnblogs.com/zhenyulu/articles/62720.html

Author's rain in November

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.