How to use JavaScript verification mode

Time:2022-5-14
catalogue
  • summary
  • Form validation without policy mode
  • Use policy pattern optimization
  • Advantages of strategic mode
  • summary

summary

In the web project, the login, registration and other functions require form submission. Before submitting the user’s data to the background, the front end generally needs to do some verification within its ability, such as whether to fill in, the length of filling in, whether the password meets the specifications, etc. the front end verification can avoid submitting non-standard forms.

If we have a form, the verification logic is as follows:

  • User name cannot be empty
  • The password length shall not be less than 6 digits
  • Mobile phone number conforms to format

Form validation without policy mode

When the policy mode is not used, that is, the verification mode we will first think of is usually as follows:

<body>
    <form>
        < label for = "username" > enter user name: < input type = "text" name = "username" > < / label >
        < label for = "password" > enter password: < input type = "password" name = "password" > < / label >
        < label for = "phone" > enter password: < input type = "text" name = "phone" > < / label >
    </form>
    <script>
        const form = document.querySelector('.registerForm');
        form.onsubmit = function(){
            if(form.username.value === ''){
                Alert ('user name cannot be empty ')
                return;
            }
            if(form.password.value.length < 6){
                Alert ('password length cannot be less than 6 digits')
                return;
            }
            if(!/(^1[3|5|8][0-9]{9}$)/.test(form.phone.value)){
                Alert ('incorrect mobile number format ')
                return;
            }
        }
    </script>
</body>

This coding method is very common, but its disadvantages are also obvious:

  • The onsubmit function is too large and contains a lot of if else. It needs to cover all rules
  • The onsubmit function lacks flexibility. If you want to enter a new verification rule, you must change the content implementation of the function and violate the open close principle
  • The code reusability is poor. If you write another form, you will have to copy a lot of duplicate code

Use policy pattern optimization

First, encapsulate the check function as an object:


const strategies = {
    empty(value, errMsg){
        if(value.length === 0){
            return errMsg;
        }
    },
    minLength(value, len, errMsg){
        if(value.length < len){
            return errMsg;
        }
    },
    isMobile(value, errMsg){
        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){
            return errMsg;
        }
    }
}

We also need a validator class, which is used to add validation rules to the target form. Its usage is as follows:

const validate = function(){
    const validator = new Validator();
    validator. Add (form. Username, 'empty', 'username cannot be empty');
    validator. Add (form. Password, 'minlength: 6', 'password length cannot be less than 6 digits');
    validator. Add (form. Phone, 'ismobile', 'incorrect mobile number format');
    const errMsg = validator.start();
    return errMsg;
}

As shown in the code, the validator instance has an add method that receives three parameters. The first is the form instance to be verified, the second is the verification method, and the passed in parameters are followed by the colon. The third is the error message that the verification failed.

The start method is used to start the verification. If it fails, a prompt message of failure will be returned, which can be processed in the subsequent logic

Preparation of validator class:


class Validator {
    constructor(){
        this.rules = [];
    }
    add(elem, rule, err){
        const args_arr = rule.split(":");
        this.rules.push(()=>{
            const handler = args_arr.shift();
            args_arr.unshift(elem.value);
            args_arr.push(err);
            return strategies[handler].apply(elem, args_arr)
        })
    }
    start(){
        let errmsg = []
        for(let i = 0; i < this.rules.length; i++ ){
            const err = this.rules[i]();
            if(err){
                errmsg.push(err)
            }
        }
        return errmsg.join(",");
    }
}

Using the policy mode, we use the configuration method to complete the verification of forms. These rules can be used in any place to verify forms in the future, which is more convenient for modification and reuse

Add multiple validation rules for a single form item

One disadvantage of our code is that it can only assign a single validation rule to a form item, and cannot implement multiple validation rules for a form, so the code still has room for optimization

class Validator{
    // ···
    add(elem, rules){
        rules.forEach(rule => {
            const args_arr = rule.strategy.split(":");
            this.rules.push(()=>{
                const handler = args_arr.shift();
                args_arr.unshift(elem.value);
                args_arr.push(rule.errMsg);
                return strategies[handler].apply(elem, args_arr)
            })
        });
    }
    // ···
}

const validate = function(){
    const validator = new Validator();
    validator.add(Form.username,[{
        strategy: 'empty',
        Errmsg: 'user name cannot be empty'
    }]);
    validator.add(Form.password, [{
        strategy: 'minLength:6',
        Errmsg: 'password length cannot be less than 6 digits'
    }]);
    validator.add(Form.phone, [{
        strategy: 'isMobile',
        Errmsg: 'the mobile phone number format is incorrect'
    }, {
        strategy: 'empty',
        Errmsg: 'mobile number cannot be empty'
    }]);
    const errMsg = validator.start();
    return errMsg;
}

Just pass in an object array when passing parameters, and add the corresponding array processing logic in the add function

Advantages of strategic mode

advantage:

  • Avoid multiple conditional selection statements
  • The principle of opening and closing is realized, which makes the use of functions easier to switch, understand and expand.
  • Improve code reuse

summary

Peter Norvig said that in a language in which a function is a first-class object, the strategy mode is invisible, and strategy is a variable whose value is a function. In fact, it is to pass the encapsulated policy function as a parameter to the target using it. The process called by the target, and make good use of the policy mode, not only let us have a deeper understanding of the mode, but also let us understand the benefits of using the function.

The above is the details of how to use JavaScript policy mode to verify the form. For more information about JavaScript, please pay attention to other related articles of developeppaer!

Recommended Today

Mysql8 new feature CTE recursive implementation 30 day time date

WITH RECURSIVE dates (date) AS ( SELECT DATE_SUB(CURDATE(), INTERVAL 30 DAY) FROM DUAL UNION ALL SELECT date + INTERVAL 1 DAY FROM dates WHERE date + INTERVAL 1 DAY <= (SELECT CURDATE() from DUAL) ) SELECT * FROM dates ORDER BY dates.date desc ;   SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL ac DAY), ‘%Y-%m-%d’) AS DATE FROM ( […]