表单:
:rules="[{ pattern:ageRules, message: '请填写密码' }]"
data:
telRules:[{ required:true, message: '手机号不能为空', trigger:blur, },{ validator: value => { return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/ .test(value) }, message: '请输入正确的手机号格式', trigger: 'onBlur', }],
表单:
:rules="[{ pattern:ageRules, message: '请填写密码' }]"
data:
ageRules: /^[0-9]{3,7}$/,
(ps:就是在这里遇到小坑,按照文档自己写发现只有函数名是validator的校验方法能生效,后来才想明白通过validator:名字 的方式可以指定。被自己蠢哭了...)
表单:
:rules="[{ validator:ur, message: '请输入正确内容' }]"
data:
ur(val) { return /^[0-9]{3,7}$/.test(val); },
<template> <div> <h2>表达校验</h2> <van-form @submit="onSubmit"> <!-- 函数校验 --> <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名" :rules="[{ validator:ur, message: '请输入正确内容' }]" /> <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" /> <!-- 正则校验 --> <van-field v-model="mobile" name="手机号" label="手机号" placeholder="请输入手机号" :rules="telRules" /> <van-field v-model="username" name="年龄" label="年龄" placeholder="年龄" :rules="[{ pattern:ageRules, message: '请填写密码' }]" /> <div style="margin: 16px;"> <van-button round block type="info" native-type="submit">提交</van-button> </div> </van-form> </div> </template> <script> export default { name: "goodsModel", data() { return { username: '', password: '', mobile:'', ageRules: /^[0-9]{3,7}$/, /** 表单校验 */ telRules:[{ required:true, message: '手机号不能为空', trigger:blur, },{ validator: value => { return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/ .test(value) }, message: '请输入正确的手机号格式', trigger: 'onBlur', }], } }, methods: { ur(val) { return /^[0-9]{3,7}$/.test(val); }, onSubmit(values) { console.log('submit', values); }, } } </script> <style scoped> </style>
参考博客:
https://blog.csdn.net/weixin_42322454/article/details/113143385