因项目需求用到表单验证,但是网上缺少直接能用的,通过借鉴加以改造,用引用cdn的形式,可以直接打开html文件,不用搭建vue项目,便于参考学习,后期慢慢增补用到的表单验证。
参考链接 https://blog.csdn.net/weixin_42018790/article/details/80762149 git地址 https://gitee.com/thinkerwing/study/tree/master/vue2/%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81 表单验证少不了正则表达式的学习,附上链接,防丢失。 https://deerchao.cn/tutorials/regex/regex.htm https://developer.mozilla.org/zh-CN/docs/orphaned/Web/JavaScript/Guide/Regular_Expressions
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.el-form-item__content{
margin-left: 0!important;
}
</style>
</head>
<body>
<div id="app">
<el-form ref="form" :rules="rules" :model="form" label-width="300px">
<el-form-item label="发货人电话" prop="phone">
<el-input v-model="form.phone"></el-input>
<el-button>确认</el-button>
</el-form-item>
</el-form>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.3/index.js"></script>
<script>
const app = new Vue({
el: '#app',
data() {
// 此处自定义校验手机号码js逻辑
var phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
var validatePhone = (rule, value, callback) => {
if (!value) {
return callback(new Error('号码不能为空!!'))
}
setTimeout(() => {
if (!phoneReg.test(value)) {
callback(new Error('格式有误'))
} else {
callback()
}
}, 100)
}
return {
form: {
phone: '',
},
// 校验规则
rules: {
// 校验手机号码,主要通过validator来指定验证器名称
phone: [{
required: true, // required就是这个框必须填写
validator: validatePhone, // 规则
trigger: 'blur' // blur失去焦点,事件何时触发
}]
},
}
}
});
</script>
</body>
</html>
|