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

news/2024/7/3 14:39:26
有意取而不得,失落而归。无意间有所获,未有喜悦,但珍惜依旧

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文件: https://github.com/chenhuiYj/...

demo文件:https://github.com/chenhuiYj/...

4.小结

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

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

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

图片描述图片描述


http://www.niftyadmin.cn/n/4190052.html

相关文章

linux-centos7设置tomcat开机自启

找到/etc/rc.d/文件下的rc.local&#xff0c;添加如下内容 export JAVA_HOME/usr/local/jdk1.8.0_144export JRE_HOME$JAVA_HOME/jre sh /usr/local/tomcat1-8080/bin/startup.shsh /usr/local/tomcat2-8081/bin/startup.sh12345sh /usr/tomcat/apache-tomcat-9.0.0.M1-80/bin/…

【AI】图像识别-物体检测-百度AI-EasyDL-NodeJS

var https require(https) var express require(express); var app express(); var bodyParser require("body-parser"); var request require(request) var fs require(fs); // 引入fs模块//访问端口 var port 9999//接受post数据 app.use(bodyParser.json({…

用Vue开发仿旅游站webapp项目总结 (上)

写着写着发现会写不少内容... 全部写在一篇文章里感觉太多了不方便看&#xff0c;所以分为上下篇吧...下篇写完啦&#xff0c;感兴趣的朋友可以继续关注 > Vue开发仿旅游站webapp项目总结 &#xff08;下&#xff09; 温馨提示 此文章&#xff0c;仅是做完项目后的个人觉得可…

[译] React Hooks 揭秘:数组解构融成魔法

原文地址&#xff1a;React hooks: not magic, just arrays原文作者&#xff1a;Rudi Yardley译文出自&#xff1a;掘金翻译计划本文永久链接&#xff1a;github.com/xitu/gold-m…译者&#xff1a;Xekin-FE校对者&#xff1a;Hopsken, CoderMing用模型解析此提案的执行规则 我…

greenDao中新实体添加代码无法自动生成

如上图所示&#xff0c;class必须有实体标识&#xff0c;如果没有这个标识代码无法自动生成 如果所示Id是一个记录标识&#xff0c;有时候不能丢掉。转载于:https://www.cnblogs.com/liuniublogs/p/9956129.html

封装axios方法之一

一、先来说说为什么要封装axios异步请求。 我们前端开发中总是会遇到跨域的问题&#xff0c;我们会配置proxy来解决跨域的问题&#xff0c;无论是vue 还是react。 如何配置我这里就不说了。 然后...然后我们就会遇到一个打包上线的问题&#xff0c;上线时候我们必须把前缀拼接上…

属于程序员自己的日历 2019年编程日历限量预售!

11.14&#xff0c;宜码代码日历一天天地翻过&#xff0c;转眼间 2018 年开始进入了倒计时。这一年&#xff0c;小伙伴们有怎样的收获&#xff1f;年初时信心满满立下了众多 Flag&#xff0c;如今都实现了没&#xff1f; 日子过得飞快&#xff0c;去年年初为大家包装日历的画面仿…

样条表示---B样条曲线

2019独角兽企业重金招聘Python工程师标准>>> B样条曲线 B样条曲线公式 均匀周期性B样条曲线 三次周期性B样条曲线 开放均匀的B样条曲线 非均匀B样条曲线 转载于:https://my.oschina.net/liyangke/blog/2875941