vant中给van-field添加正则一定要在van-form中
在van-field标签上声明一个rules属性,把它复制给一个data中变量,在data中声明这个变量。该变量的形式为一个数组,里面有一个元素为对象,对象的第一个属性为pattern是你需要校验的正则表达式,第二个属性为message是错误后的提示文字,第三个属性为trigger是什么时候触发正则检验van-field。
下面是代码演示:
<van-form ref="form" @failed="onFailed" @submit="onSubmit">
<p class="zh"><van-field name="zh" :rules="zhrules" label-width="8.4rem" colon v-model="username" label="账号"/></p>
<p class="psw"><van-field name="psw" :rules="pswrules" label-width="8.4rem" colon v-model="password" label="密码" /></p>
</van-form>
export default {
data () {
return {
username: '',
password: '',
zhrules: [{ required: true, message: '账号不能为空', trigger: 'onBlur' }, { pattern: /^[\w-]{4,16}$/, message: '账号格式错误', trigger: 'onBlur' }],
pswrules: [{ required: true, message: '密码不能为空', trigger: 'onBlur' }, { pattern: /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/, message: '密码格式错误', trigger: 'onBlur' }]
}
}
}