Home Web Front-end JS Tutorial JavaScript design pattern--Strategy pattern input validation_javascript skills

JavaScript design pattern--Strategy pattern input validation_javascript skills

May 16, 2016 pm 03:29 PM

The strategy pattern defines a family of algorithms and encapsulates them separately so that they can be replaced with each other. This pattern makes the algorithm changes independent of the customers who use the calculation.

First define a simple input form:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-">
    <style>
      .form{
        width: px;
        height: px;
        #margin: px auto;
      }
      .form-item-label{
        width:px;
        text-align: right;
        float: left;
      }
      .form-item-input{
        float: left;
      }
      .form-item{
        width: % ;
        height: px;
        line-height: px;
      }
    </style>
  </head>
  <body>
    <div class='form'>
      <div class="form-item">
        <div class='form-item-label'><span>用户名:</span></div>
        <div class='form-item-input'><input id='userName' name='用户名' type="text"></div>
      </div>
      <div class="form-item" >
        <div class='form-item-label'><span>密码:</span></div>
        <div class='form-item-input'><input id='password' name='密码' type="text"></div>
      </div>
      <div class="form-item" >
        <div class='form-item-label'><span>确认密码:</span></div>
        <div class='form-item-input'><input id='repassword' name='密码确认' type="text"></div>
      </div>
      <div class="form-item" >
        <div class='form-item-label'><span>邮箱:</span></div>
        <div class='form-item-input'><input id='mail' name='邮箱' type="text" ></div>
      </div>
    </div>
    <br>
    <button id='submit' >提交</button>
    <script type='text/javascript' src="../reference/jquery-...min.js"></script>
  </body>
</html>
Copy after login

Generally, in the submission action after editing information on the page, the input information needs to be verified. You will see that a lot of code responsible for checking is written in the submission function or in an independent check function.

For example, like below.         

 $(document).ready(function(){
        $('#submit').bind('click', doSubmit);
      });
      function doSubmit(){
        var eleUserName = document.getElementById('userName');
        if(eleUserName.value === '') {
          alert('用户名不能为空');
          return;
        }
        if(eleUserName.length < 6) {
          alert('用户名长度不能少于6个字符');
          return;
        }
        if(eleUserName.length > 6) {
          alert('用户名长度不能多于20个字符');
          return;
        }
      }
Copy after login

This writing method can definitely meet the functional requirements, but there will be several problems:

1. If I want to use it on other pages, I have to copy the code. The so-called reuse becomes copying, and there will be a lot of duplication of the code. Better ones will classify and package the check code, but there will be more duplication.

2. If I want to add an input verification, then I have to directly modify the submission function. This function will be bloated and destroy the "opening and closing" principle.

3. If you modify the submission function, you must cover all the tests of the function design, because you don’t know when mistaken changes or unknown situations will occur.

Transformation steps:

1. Treat each verification logic as a verification strategy and encapsulate each verification strategy function. The function parameters should be consistent and can accept DOM elements, verified values, error messages, and customized parameters.

2. Define the validator, you can import the validation strategy function or add it.

3. The validator provides a verification method for calling during verification, and internally calls a specific verification strategy function.

4. Verify the call.

Step 1.

Consider each if as a verification business rule, treat each business rule as a separate strategy function, and encapsulate all strategy functions into a strategy object.                           

 var validationStrategies = {
        isNoEmpty: function(element, errMsg, value) {
          if(value === '') {
            return this.buildInvalidObj(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-&#63;)+(\.\w{2,})+$/;
          if(!reg.test(value)){
            return this.buildInvalidObj(element, errMsg, value);
          }
        }
      };
Copy after login

The first three parameters of all functions are consistent and required, indicating the verified DOM element, error message, and verified value. The fourth one starts with the function’s own verification rules to determine the customized parameters. Can have multiple parameters.

The "buildInvalidObj" method just converts the first three parameters into an error object and returns it. This error object will be returned as long as the verification fails.

According to the dependency inversion principle, high-level modules should not depend on low-level modules, so they cannot be used directly by the caller of verification.

Encapsulation and abstraction through validators.

Step 2:

Define the validator, you can import all the verification strategies into it, or you can add the verification strategy functions separately.                                                          

//输入验证器
      function InputValidators(){
        this.validators = [];
        this.strategies = {};
      }
      //从策略对象导入验证策略函数
      //参数:
      // strategies: 包含各种策略函数的对象
      InputValidators.prototype.importStrategies = function(strategies) {
        for(var strategyName in strategies) {
          this.addValidationStrategy(strategyName, strategies[strategyName]);
        }
      };
      //添加验证策略函数
      //参数:
      // name: 策略名称
      // strategy: 策略函数
      InputValidators.prototype.addValidationStrategy = function(name, strategy){
        this.strategies[name] = strategy;
      };
Copy after login

Step 3:

Add verification method to accept external calls.

The first parameter rule is set to a verification rule, such as "minLength:6". The following code will generate a call to the specific strategy function. The call will be pushed into the cache and wait to be called together.

":6" indicates the parameters customized by the strategy function according to its own rules.       

  //添加验证方法
      //参数:
      // rule: 验证策略字符串
      // element: 被验证的dom元素
      // errMsg: 验证失败时显示的提示信息
      // value: 被验证的值
      InputValidators.prototype.addValidator = function(rule, element, errMsg, value) {
        var that = 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);
        });
      };
Copy after login
Call all verifications through a check function. and return incorrect results.         

   //开始验证
      InputValidators.prototype.check = function() {
        for(var i = 0, validator; validator = this.validators[i++];){
          var result = validator();
          if(result) {
            return result;
          }
        }
      };
Copy after login

Step 4:

Where verification is required, first create a new validator object.                                                                       


var validators = new InputValidators();
Copy after login
Import the object containing the verification strategy function, or add the verification strategy function separately.                                                                        

It can be seen that different verification strategies can be pre-encapsulated into the strategy object, or can be added immediately according to the actual situation.
  validators.importStrategies(validationStrategies);
        validators.addValidationStrategy('isEqual', function(element, errMsg, value1, value2) {
          if(value1 !== value2) {
            return this.buildInvalidObj(element, errMsg, value1 );
          }
        });
Copy after login
Then add the strategy that needs to be verified, the verified DOM element, the error message, and the verified value into the validator by adding a verification method. This avoids directly calling the strategy object and reduces the coupling.

Call the validator's check to perform all verifications.                                                                     
var eleUserName = document.getElementById('userName');
validators.addValidator('isNoEmpty', eleUserName, '用户名不能为空', eleUserName.value);
validators.addValidator('minLength:6', eleUserName, '用户名的字符个数必须是6到20个', eleUserName.value);
validators.addValidator('maxLength:20', eleUserName, '用户名的字符个数必须是6到20个', eleUserName.value);
var elePassword = document.getElementById('password');
validators.addValidator('isNoEmpty', elePassword, '密码不能为空', elePassword.value);
validators.addValidator('minLength:6', elePassword, '密码的字符个数必须是6到20个', elePassword.value);
validators.addValidator('maxLength:20', elePassword, '密码的字符个数必须是6到20个', elePassword.value);
var eleRepassword = document.getElementById('repassword');
validators.addValidator('isNoEmpty', eleRepassword, '确认密码不能为空', eleRepassword.value);
validators.addValidator('minLength:6', eleRepassword, '确认密码的字符个数必须是6到20个', eleRepassword.value);
validators.addValidator('maxLength:20', eleRepassword, '确认密码的字符个数必须是6到20个', eleRepassword.value);
validators.addValidator('isEqual:' + elePassword.value, eleRepassword, '两次密码不一致', eleRepassword.value);
var eleMail = document.getElementById('mail');
validators.addValidator('isNoEmpty', eleMail, '邮箱不能为空', eleMail.value);
validators.addValidator('isMail', eleMail, '邮箱不是一个有效的格式', eleMail.value);
Copy after login

check returns an error object. We can use this object to uniformly perform prompt operations on DOM elements after check, such as setting focus, selecting content, or wrapping a layer of red style on the outside of the input box.
var result = validators.check();
        if(result){
          alert(result.errMsg);
          result.element.focus();
          result.element.select();
          return false;
        }
Copy after login
At this point, we can see that through the change of the strategy mode, when input verification, we only need to care about which verification rule to use and what kind of prompt information to use. The implementation details are no longer exposed, which is convenient for calling and subsequent follow-up. Extension and componentization.

All codes:

The above is the entire content of the javascript design pattern introduced by the editor - strategy pattern input verification. I hope you like it.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles