[无心插柳]简单实现常用的表单校验函数

62,414 阅读7分钟

有意取而不得,失落而归。无意间有所获,未有喜悦,但珍惜依旧

1.前言

表单校验,相信绝大部分的开发者会遇到过,网上也有很多插件可使用。但当时想着就是简单的校验,没必要引插件,就自己写一个简单的函数。随着校验的需求多样化,函数越来越大。有点轮子的雏形,算是无心插柳吧。现在也该分享出来了,和大家交流交流。函数比较粗糙,如果大家有建议,评论留言吧。

1.关于实现的过程,原理都是参考了《JavaScript设计模式与开发实践》策略模式的一个例子。代码比较简单,大家移步到文末的链接,下载相关的文件,运行调试下就会知道是当中的奥秘了。这里就不做过多的介绍,只展示出可以应付哪些校验场景和使用的方法。

2.虽然我开发项目中会使用这个函数,但今天的文章,主要是出于分享和交流学习,介绍下这种表单校验的方式。目前函数比较粗糙,功能不够强大,待完善,在项目中使用要注意谨慎。

3.文章例子依赖 vue ,只为了方便展示,该函数为原生 js 函数。

2.表单校验的场景

首先,简单列举下表单校验的常用场景

2-1.基础数据校验

关于下面调用的规则:rule,全部封装在这个文件下面的ruleData这个变量这里。一看就知道怎么回事了。提供了常用的校验规则,需要的可以扩展。

调用代码

<div id="form-box">
    <!--校验单个字段-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入姓名" v-model="demo1.userName"></p>
        <p class="u-tips">{{demo1.tips.userName}}</p>
        <p><input type="text" class="u-input-text" placeholder="请输入电话或者邮箱" v-model="demo1.userContact"></p>
        <p class="u-tips">{{demo1.tips.userContact}}</p>
        <p><input type="button" class="u-btn-submit" value="提交" @click="handleSubmit1"></p>
    </div>
</div>
new Vue({
    el: '#form-box',
    data: {
        demo1: {
            userName: '',
            userContact: '',
            tips: ''
        }
    },
    methods: {
        handleSubmit1(){
            let _this = this;
            let _tips=ecValidate.check([
                {
                    //校验的数据
                    el: _this.demo1.userName,
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '姓名不能为空'}
                    ],
                },
                {
                    //校验的数据
                    el: _this.demo1.userContact,
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '联系方式不能为空'}, 
                        {rule: 'isMobile', msg: '请输入正确的联系方式'}
                    ]
                }
            ])
            this.demo1.tips = _tips;
        }
    }
})

2-2.多种校验规则

输入电话或者邮箱都可以

调用代码

<div id="form-box">
    <!--...-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入姓名" v-model="demo2.userName"></p>
        <p><input type="text" class="u-input-text" placeholder="请输入电话或者邮箱" 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="提交" @click="handleSubmit2"></p>
    </div>
</div>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo2: {
            userName: '守候',
            userContact: '',
            tips: ''
        },
    },
    methods: {
        //...
        handleSubmit2(){
            let _this = this;
            let _tips=ecValidate.check([
                {
                    //校验的数据
                    el: _this.demo2.userName,
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '姓名不能为空'}
                    ],
                },
                {
                    //校验的数据
                    el: _this.demo2.userContact,
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '联系方式不能为空'}, 
                        {rule: 'isMobile,isEmail', msg: '请输入正确的联系方式'}
                    ]
                }
            ])
            this.demo2.tips = _tips;
        }
    }
})

2-3.扩展校验规则

比如要增加一个校验规则:名字只能是中文(只能输入中文,这个规则已经收录了,这里只作为展示使用)

<div id="form-box">
    <!--...-->
    <!--单个字段,扩展规则-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入姓名" 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="提交" @click="handleSubmit3"></p>
    </div>
</div>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo3: {
            userName: '',
            tips: ''
        },
    },
    methods: {
        //...
        handleSubmit3(){
            let _this = this;
            let _tips=ecValidate.check([
                {
                    //校验的数据
                    el: _this.demo3.userName,
                    //校验的规则(使用在 mounted 的扩展语法)
                    rules: [
                        {rule: 'isNoNull', msg: '姓名不能为空'},
                        {rule: 'isChinese', msg: '姓名只能输出中文'}
                    ],
                }
            ])
            this.demo3.tips = _tips;
        }
    },
    mounted:function () {
        //添加扩展规则
        ecValidate.addRule('isChinese',function (val, msg) {
            return !/^[\u4E00-\u9FA5]+$/.test(val) ? msg : '';
        })
    }
})

2-4.数据有误,定位第一个有误的数据

调用代码

<div id="form-box">
    <!--...-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入姓名" 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="请输入电话或者邮箱" 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><input type="button" class="u-btn-submit" value="提交" @click="handleSubmit4"></p>
    </div>
</div>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo4: {
            userName: '',
            userContact: '',
            tips: {}
        },
    },
    methods: {
        //...
        handleSubmit4(){
                let _this = this;
                //在校验数组里面加上alias字段,保存错误信息。该字段要保证值唯一性,并且要么全部加上,要么全部不加,不然可能会造成页面错误
                let _tips=ecValidate.check([
                    {
                        //校验的数据
                        el: _this.demo4.userName,
                        alias: 'userName',
                        //校验的规则
                        rules: [
                            {rule: 'isNoNull', msg: '姓名不能为空'}
                        ],
                    },
                    {
                        //校验的数据
                        el: _this.demo4.userContact,
                        alias: 'contact',
                        //校验的规则
                        rules: [
                            {rule: 'isNoNull', msg: '联系方式不能为空'},
                            {rule: 'isMobile,isEmail', msg: '请输入正确的联系方式'}
                        ]
                    }
                ])
                this.demo4.tips = _tips;
            }
        },
    },
    mounted:function () {
        
    }
})

2-5.哪些数据有误,定位有误的数据

调用代码

<div id="form-box">
    <!--...-->
    <!--校验全部-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入姓名" 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="请输入电话或者邮箱" 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><input type="button" class="u-btn-submit" value="提交" @click="handleSubmit5"></p>
    </div>
</div>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo5: {
            userName: '',
            userContact: '',
            tips: {}
        },
    },
    methods: {
        //...
        handleSubmit5(){
            let _this = this;
            //checkAll校验全部的函数,必须要加上alias字段。
            let _tips=ecValidate.checkAll([
                {
                    //校验的数据
                    el: _this.demo5.userName,
                    alias: 'userName',
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '姓名不能为空'}
                    ],
                },
                {
                    //校验的数据
                    el: _this.demo5.userContact,
                    alias: 'contact',
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '联系方式不能为空'}, 
                        {rule: 'isMobile,isEmail', msg: '请输入正确的联系方式'}
                    ]
                }
            ])
            this.demo5.tips = _tips;
        },
    },
    mounted:function () {
        
    }
})

2-6.实时校验

调用代码

<div id="form-box">
    <!--...-->
    <!--单个输入,实时校验-->
    <div class="m-from-box">
        <p><input type="text" class="u-input-text" placeholder="请输入电话或者邮箱" 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>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo6: {
            userContact: '',
            tips:'',
        },
    },
    methods: {
        //...
        handleInput6(){
            let _this = this;
            let _tips=ecValidate.check([
                {
                    //校验的数据
                    el: _this.demo6.userContact,
                    //校验的规则
                    rules: [
                        {rule: 'isNoNull', msg: '联系方式不能为空'}, 
                        {rule: 'isMobile,isEmail', msg: '请输入正确的联系方式'}
                    ]
                },
            ])
            this.demo6.tips = _tips;
        },
    },
    mounted:function () {
        
    }
})

2-7.实时校验,其他校验规则

比如密码强度和长度的校验

调用代码

<!--单个输入,实时校验-密码强度-->
<div class="m-from-box">
    <p><input type="text" class="u-input-text" placeholder="请输入密码" v-model="demo7.pwd"  @input="handleInput7"></p>
    <p class="u-tips" :class="'lv'+demo7.tips" v-if="demo7.tips.constructor===Number">密码强度:{{demo7.tips}}</p>
    <p class="u-tips" :class="'lv'+demo7.tips" v-else>{{demo7.tips}}</p>
</div>
new Vue({
    el: '#form-box',
    data: {
        //...
        demo7: {
            pwd:'',
            tips: '',
        }
    },
    methods: {
        handleInput7(){
                let _this = this;
                let _tips=ecValidate.check([
                    {
                        //校验的数据
                        el: _this.demo7.pwd,
                        //校验的规则
                        //由于检查密码强度规则 pwdLv 是实时返回密码强度,并非报错信息。所以该规则要放置在最后
                        rules: [
                        	{rule: 'minLength:6', msg: '密码长度不能小于6'},
                        	{rule: 'maxLength:16', msg: '密码长度不能大于16'},
                            {rule: 'pwdLv'}
                        ]
                    },
                ])
                //判断 _tips 是否是数字
                this.demo7.tips = _tips.constructor===Number?+_tips:_tips;
        },
    },
    mounted:function () {
        
    }
})

感觉密码强度这样写法有点鸡肋,也不方便,这个是重点优化部分。

2-8.校验数据类型

比如下面检测的是一个数据是否是数组类型

调用代码

let tips=ecValidate.check([
    {
        el:'[1,2,3,4,5]',
        rules:[{rule:'isType:array',msg:'传进去的数组不是数组'}]
    }
]);
console.log(tips);

用到的文件就是下面两个,也欢迎大家 star 一下。

js文件:github.com/chenhuiYj/e…

demo文件:github.com/chenhuiYj/e…

4.小结

关于表单的一些常用校验,就暂时写到这里了,这个无心插柳的作品,现在还比较粗糙,以后还要有很长的修改优化之路。也欢迎大家在评论区提出一些建设性的意见,当交流也好。

-------------------------华丽的分割线--------------------

想了解更多,和我交流,内推职位,请添加我微信。或者关注我的微信公众号:守候书阁