登录校验页面
<script setup lang="ts">
import { ref } from 'vue'
import { mobileRules, passwordRules } from '@/utils/rules'
const mobile = ref('')
const password = ref('')
</script>
<!-- 表单 --><van-form autocomplete="off"><van-fieldv-model="mobile":rules="mobileRules"placeholder="请输入手机号"type="tel"></van-field><van-fieldv-model="password":rules="passwordRules"placeholder="请输入密码"type="password"></van-field>
封装校验页面utils/rules.ts
提取表单校验规则(为了其他页面复用)
加上 FieldRule ,可以有提示,提高效率
import type { FieldRule } from 'vant'
const mobileRules = [{ required: true, message: '请输入手机号' },{ pattern: /^1[3-9]\d{9}$/, message: '手机号不正确' }
]
const passwordRules: FieldRule[] = [{ required: true, message: '请输入密码' },{ pattern: /^\w{8,24}$/, message: '密码必须是8-24个字符' }
]
export { mobileRules, passwordRules }
效果图:
表单整体校验
加上native-type=“submit”,只有是submit时才能触发校验,这样点击登录就可以实现整体校验
" native-type" 是按钮的原始类型,通常用于表示某种原生的类型。
<div class="cp-cell"><van-button native-type="submit" block round type="primary">登 录</van-button></div>
复选框校验
//默认为false不勾选
const agree = ref(false)
const onSubmit = () => {
//如果agree.value不存在,也就是值为false,则提示勾选if (!agree.value) {return showToast('请勾选协议')}console.log(111)
}
submit提交表单且验证通过后触发
<van-form autocomplete="off" @submit="onSubmit"><div class="cp-cell"><van-checkbox v-model="agree"><span>我已同意</span><a href="javascript:;">用户协议</a><span>及</span><a href="javascript:;">隐私条款</a></van-checkbox></div></van-form>