vue+element项目 手机号、邮箱校验 保姆级教程 (包含注意点)
先看案例:在vue+element项目中给表单中的手机号和邮箱做校验
标题先说注意点 prop黄色框框起来的一定要有
废话不多说上代码
一、hmtl部分
<el-form
:model="modifyForm"
:rules="rules"
ref="modifyFormRef"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="手机" prop="mobile">
<el-input v-model.number="modifyForm.mobile" maxlength="11"
></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="modifyForm.email"></el-input>
</el-form-item>
<el-form-item class="tijiao">
<el-button plain @click="handleCancel">取消</el-button>
<el-button type="primary" @click="add()">新建</el-button>
</el-form-item>
</el-form>
二、js部分
<script>
export default {
components: {
},
data() {
/* 手机号 */
var isMobileNumber = (rule, value, callback) => {
if (!value) {
return new Error('请输入电话号码')
} else {
const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
const isPhone = reg.test(value)
value = Number(value) //转换为数字
if (typeof value === 'number' && !isNaN(value)) {
//判断是否为数字
value = value.toString() //转换成字符串
if (value.length < 0 || value.length > 12 || !isPhone) {
//判断是否为11位手机号
callback(new Error('手机号码格式如:138xxxx8754'))
} else {
callback()
}
} else {
callback(new Error('请输入电话号码'))
}
}
}
/* 邮箱 */
var isEmail = (rule, value, callback) => {
if (!value) {
callback()
} else {
const reg =
/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
const email = reg.test(value)
if (!email) {
callback(new Error('邮箱格式如:admin@163.com'))
} else {
callback()
}
}
}
return {
/* 校验规则 */
rules: {
mobile: [
{ required: true, message: '请输入手机号码', trigger: 'blur' },
{ validator: isMobileNumber, trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{ validator: isEmail, trigger: 'blur' }
],
}
}
},
created() {},
methods: {}
}
</script>
三、友情提醒记得对应好你那边的字段
(全网最清晰的vue+element项目 手机号、邮箱校验、保姆级教程,你还在等什么CV就完事了。)
四、调用添加接口
提交的按钮
<el-button type="primary" @click="add()">新建</el-button>
需要提交的参数 与 rules平级
modifyForm: {
ddress: '',
mobile: '',
email: '',
sex: true,
sources: '',
wxNickname: '',
prefecture: ''
},
/* 添加功能的规则校验 */
async add() {
this.$refs.modifyFormRef.validate((valid) => {
/* 如果不符合校验就返回 */
if (!valid) return
/* 符合校验调用添加接口 */
this.handleAdclick()
})
},
/* 调添加接口 */
async handleAdclick() {
/* modifyForm为需要传递的参数 */
const result = await addCustomer(this.modifyForm)
if (result.code === 200) {
/* 添加完置空表单 */
this.modifyForm = {
address: '',
mobile: '',
email: '',
sex: true,
sources: '',
wxNickname: '',
prefecture: ''
}
this.$message.success('添加成功')
this.$router.go(-1)
} else {
this.$message.error('添加失败')
}
}
温馨提示:如果以上方法尝试过了,问题还没解决的朋友,如果您不嫌弃,欢迎评论或者私信联系,我会第一时间与您取得联系,和您一起探讨解决问题!绝不收取任何咨询费用!
关键词搜索优化(与文章无关):vue+element项目 手机号、邮箱校验 保姆级教程,手机号、邮箱表单校验 手机号、邮箱表单校验不灵 有问题 无法校验。