Intended to take but not, lost and return. Inadvertently acquired, no joy, but cherish

1. Introduction

Form verification, I believe that most developers will encounter, there are many plug-ins available online. But at that time, I thought it was a simple check, no need to introduce plug-ins, write a simple function. As the requirements for verification vary, the functions become larger and larger. It’s kind of a wheel. It’s kind of an accident. Now is the time to share it, to communicate with everyone. If you have any suggestions, please leave a comment.

1. As for the implementation process, the principle is an example of the strategy pattern referenced in JavaScript Design Patterns and Development Practices. The code is relatively simple, we go to the link at the end of the article, download the relevant file, run the debugging will know is among the mysteries. I won’t go into too much detail here, but just show what validation scenarios can be handled and how to use them.

2. Although I will use this function in my development projects, today’s article mainly introduces this form verification method for sharing and exchange learning. At present, the function is rough and not powerful enough. It needs to be improved, so it should be used carefully in the project.

3. The examples in this article rely on Vue, which is a native JS function, just for demonstration purposes.

2. Form verification scenario

First, the common scenarios for form verification are briefly listed below

2-1. Basic data verification

The following rules are called: rule, all wrapped in the ruleData variable at the bottom of this file. You can see what’s going on. Provides common verification rules, you can expand the need.

The calling code

<div id="form-box"> <! Verify a single field --> <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your name" v-model="demo1.userName"></p>
        <p class="u-tips">{{demo1.tips.userName}}</p>
        <p><input type="text" class="u-input-text" placeholder="Please enter your phone number or email address." v-model="demo1.userContact"></p>
        <p class="u-tips">{{demo1.tips.userContact}}</p>
        <p><input type="button" class="u-btn-submit" value="Submit" @click="handleSubmit1"></p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        demo1: {
            userName: ' ',
            userContact: ' ',
            tips: ' '
        }
    },
    methods: {
        handleSubmit1() {let _this = this;
            let_tips= ecvalidate. check([{el: _this.demo1.userName, // check rules: [{rule:'isNoNull', msg: 'Name cannot be empty'}],}, {// check the data el: _this.demo1.usercontact, // check the rules: [{rule:'isNoNull', msg: 'Contact information cannot be empty'}, 
                        {rule: 'isMobile', msg: 'Please enter the correct contact information'} ] } ]) this.demo1.tips = _tips; }}})Copy the code

2-2. Various verification rules

Enter your phone number or email address

The calling code

<div id="form-box"> <! -... --> <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your name" v-model="demo2.userName"></p>
        <p><input type="text" class="u-input-text" placeholder="Please enter your phone number or email address." v-model="demo2.userContact"></p>
        <p class="u-tips" :class="{'success':demo2.tips==='success'}">{{demo2.tips}}</p>
        <p><input type="button" class="u-btn-submit" value="Submit" @click="handleSubmit2"></p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo2: {
            userName: 'wait',
            userContact: ' ',
            tips: ' '
        },
    },
    methods: {
        //...
        handleSubmit2() {let _this = this;
            let_tips= ecvalidate. check([{el: _this.demo2.username, // check rules: [{rule:'isNoNull', msg: 'Name cannot be empty'}],}, {// check the data el: _this.demo2.usercontact, // check the rules: [{rule:'isNoNull', msg: 'Contact information cannot be empty'}, 
                        {rule: 'isMobile,isEmail', msg: 'Please enter the correct contact information'} ] } ]) this.demo2.tips = _tips; }}})Copy the code

2-3. Extend the verification rule

For example, if you want to add a verification rule: the name can only be in Chinese.

<div id="form-box"> <! -... -- > <! -- single field, extended rule --> <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your name" v-model="demo3.userName"></p>
        <p class="u-tips" :class="{'success':demo3.tips==='success'}">{{demo3.tips}}</p>
        <p><input type="button" class="u-btn-submit" value="Submit" @click="handleSubmit3"></p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo3: {
            userName: ' ',
            tips: ' '
        },
    },
    methods: {
        //...
        handleSubmit3() {let _this = this;
            let_tips= ecvalidate. check([{el: _this.demo3.userName, // specifies the id of the ecvalidate. check({el: _this.demo3.userName, // specifies the id of the ecvalidate. check().'isNoNull', msg: 'Name cannot be empty'},
                        {rule: 'isChinese', msg: 'Name can only output Chinese'}
                    ],
                }
            ])
            this.demo3.tips = _tips;
        }
    },
    mounted:function() {// add extension rule ecvalidate.addRule ()'isChinese'.function (val, msg) {
            return! /^[\u4E00-\u9FA5]+$/.test(val) ? msg :' '; })}})Copy the code

2-4. Data error. Locate the first data error

The calling code

<div id="form-box"> <! -... --> <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your name" v-model="demo4.userName" :class="{'err':demo4.tips.userName}"></p>
        <p class="u-tips">{{demo4.tips.userName}}</p>
        <p><input type="text" class="u-input-text" placeholder="Please enter your phone number or email address." v-model="demo4.userContact" :class="{'err':demo4.tips.contact}"></p>
        <p class="u-tips">{{demo4.tips.contact}}</p>
        <p class="u-tips success" v-if="demo4.tips==='success'"</p> <p><inputtype="button" class="u-btn-submit" value="Submit" @click="handleSubmit4"></p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo4: {
            userName: ' ',
            userContact: ' ',
            tips: {}
        },
    },
    methods: {
        //...
        handleSubmit4() {let_this = this; // Add to the checksum arrayaliasField to save error information. The value of this field must be unique, and either all or none of it may cause a page errorlet_tips= ecvalidate. check([{el: _this.demo4.username,alias: 'userName'// Check the rules.'isNoNull', msg: 'Name cannot be empty'}],}, {// Check data el: _this.demo4.userContact,alias: 'contact'// Check the rules.'isNoNull', msg: 'Contact information cannot be empty'},
                            {rule: 'isMobile,isEmail', msg: 'Please enter the correct contact information'}
                        ]
                    }
                ])
                this.demo4.tips = _tips;
            }
        },
    },
    mounted:function() {}})Copy the code

2-5. Which data are wrong, and which data are located wrong

The calling code

<div id="form-box"> <! -... -- > <! <div class= ="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your name" v-model="demo5.userName" :class="{'err':demo5.tips.userName}"></p>
        <p class="u-tips">{{demo5.tips.userName}}</p>
        <p><input type="text" class="u-input-text" placeholder="Please enter your phone number or email address." v-model="demo5.userContact" :class="{'err':demo5.tips.contact}"></p>
        <p class="u-tips">{{demo5.tips.contact}}</p>
        <p class="u-tips success" v-if="demo5.tips==='success'"</p> <p><inputtype="button" class="u-btn-submit" value="Submit" @click="handleSubmit5"></p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo5: {
            userName: ' ',
            userContact: ' ',
            tips: {}
        },
    },
    methods: {
        //...
        handleSubmit5() {let_this = this; //checkAll checks all functions, which must be addedaliasField.let_tips= ecvalidate. checkAll([{el: _this.demo5.username,alias: 'userName'// Check the rules.'isNoNull', msg: 'Name cannot be empty'}],}, {// Check data el: _this.demo5.userContact,alias: 'contact'// Check the rules.'isNoNull', msg: 'Contact information cannot be empty'}, 
                        {rule: 'isMobile,isEmail', msg: 'Please enter the correct contact information'}
                    ]
                }
            ])
            this.demo5.tips = _tips;
        },
    },
    mounted:function() {}})Copy the code

2-6. Real-time verification

<div id="form-box"> <! -... -- > <! --> <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="Please enter your phone number or email address." v-model="demo6.userContact" :class="{'err':demo6.tips&&demo6.tips! =='success'}"  @input="handleInput6"></p>
        <p class="u-tips" :class="{'success':demo6.tips==='success'}">{{demo6.tips}}</p>
    </div>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo6: {
            userContact: ' ',
            tips:' ',
        },
    },
    methods: {
        //...
        handleInput6() {let _this = this;
            let_tips= ecvalidate. check([{el: _this.demo6.usercontact, // check rules: [{rule:'isNoNull', msg: 'Contact information cannot be empty'}, 
                        {rule: 'isMobile,isEmail', msg: 'Please enter the correct contact information'}
                    ]
                },
            ])
            this.demo6.tips = _tips;
        },
    },
    mounted:function() {}})Copy the code

2-7. Real-time verification and other verification rules

Such as password strength and length verification

The calling code

<! -- Single input, real-time validation -- password strength --> <div class="m-from-box">
    <p><input type="text" class="u-input-text" placeholder="Please enter your password" v-model="demo7.pwd"  @input="handleInput7"></p>
    <p class="u-tips" :class="'lv'+demo7.tips" v-if="demo7.tips.constructor===Number"> Password strength: {{demo7.tips}}</p> <p class="u-tips" :class="'lv'+demo7.tips" v-else>{{demo7.tips}}</p>
</div>
Copy the code
new Vue({
    el: '#form-box',
    data: {
        //...
        demo7: {
            pwd:' ',
            tips: ' ',
        }
    },
    methods: {
        handleInput7() {let _this = this;
                let_tips= ecvalidate. check([{// check data el: _this.demo7.pwd, // Check rules // check password strength rulespwdLv returns the password strength in real time, not an error message. So the rule should be placed last. Rules: [{rule:'minLength:6', msg: 'Password length cannot be less than 6'},
                        	{rule: 'maxLength:16', msg: 'Password length cannot be greater than 16'},
                            {rule: 'pwdLv'Constructor === =Number?+_tips:_tips;}]},]) }, }, mounted:function() {}})Copy the code

Feel password strength so writing a little chicken ribs, also not convenient, this is the key optimization part.

2-8. Verify the data type

For example, the following test checks whether a data is an array type

The calling code

let tips=ecValidate.check([
    {
        el:'[1, 2, 3, 4, 5],
        rules:[{rule:'isType:array',msg:'The array passed in is not an array.'}}]]); console.log(tips);Copy the code

The files used are the following two, and you are welcome to star.

Js file: github.com/chenhuiYj/e…

The demo file: github.com/chenhuiYj/e…

4. Summary

Some commonly used verification of forms are written here for the time being. This inadvertent work is still rough, and there will be a long way to modify and optimize in the future. You are also welcome to put forward some constructive comments in the comments section, when the exchange is good.

— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — —

If you want to know more, communicate with me and promote your position, please add me on wechat. Or follow my wechat public number: Waiting book Pavilion