<template>
<div class="from_box">
<form action="">
<ul>
<li>
姓名:
<input type="text" v-model="formMess.name">
</li>
<li>
年龄:
<input type="number" v-model="formMess.age">
</li>
<li>
体重:
<input type="number" v-model="formMess.weight">
</li>
<li>
手机:
<input type="phone" v-model="formMess.phone">
</li>
<li>
邮箱:
<input type="email" v-model="formMess.email">
</li>
<li>
地址:
<input type="text" v-model="formMess.address">
</li>
</ul>
<span @click="inspect" class="but">点击测试数据是否正确</span>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "from",
data() {
return {
formMess: {
name: '',
age: '',
weight: '',
phone: '',
email: '',
address: ''
},
checkdata:[
{
inspect: "", // 待检测的字段
msg: '姓名', // 空值返回的提示
},
{
inspect: "",
msg: '年龄'
},
{
inspect: "",
msg: '体重'
},
{
inspect: "",
msg: '手机号',
reg: '^[1][3,4,5,7,8][0-9]{9}$'
},
{
inspect: "",
msg: '邮箱',
reg: '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
},
{
inspect: "",
msg: '地址'
}
]
};
},
methods: {
// 判定是否合规
have_empty(arr) {
for (let key in arr) {
if(arr[key].inspect && arr[key].reg){ // 有值并且有规则执行验证
let reg = new RegExp(arr[key].reg)
var red_end = reg.test(arr[key].inspect)
if( !red_end ){
console.log('请输入正确的' + arr[key].msg)
return false
}
}else if(!arr[key].inspect){
console.log('请输入' + arr[key].msg)
return false
}
}
return true
},
// 判定规则前传入参数
inspect() {
this.assignData();
var end = this.have_empty(this.checkdata);
if (!end) return // 判定验证结果
console.log('执行提交的ajax函数')
},
assignData() {//赋值
var arrForm = [];
for(let key in this.formMess){
arrForm.push(key);
}
for(let i = 0;i<this.checkdata.length;i++){
var key = arrForm[i];
this.checkdata[i].inspect = this.formMess[arrForm[i]];
}
}
},
mounted() {
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.from_box{
font-size: .14rem;
form{
padding:5%;
width:90%;
margin: auto;
border:.01rem solid gray;
display: flex;
flex-wrap: wrap;
input{
width:80%;
height:.5rem;
margin-bottom: .2rem;
border:.01rem solid black;
height:.5rem;
}
}
.but{
font-size: .14rem;
margin-left:5%;
background: gray;
padding:6px;
color: #fff;
}
}
</style>
vue验证
最新推荐文章于 2022-03-22 11:21:11 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)