校验要求
我们的表单中有密码、电话号码 ,两项。
我们设置用密码为3到20位的非空字符
电话号码就用目前用的电话号码正则表达式,要求手机号码以 1 开头,第二位为 3 到 9 之间的数字,后面跟着任意 9 个数字,总共是 11 位数字。
"手机号" prop="tel"> - <el-input v-model="ruleForm.tel" :rules="rules" />
-
- <el-form-item label="密码" prop="cipher">
- <el-input v-model="ruleForm.cipher" :rules="rules" />
- el-form-item>
做类型声明:
- interface RuleForm {
- tel: string
- cipher: string
- }
然后对页面数据进行绑定:
- const rules = reactive<FormRules<RuleForm>>({
- tel: [
- { required: true, message: '请输入手机号', trigger: 'blur' },
- {
- validator: checkEmail,
- trigger: 'blur'
- },
- ],
- cipher: [
- { required: true, message: '请输入密码', trigger: 'blur' },
- {
- min: 3,
- max: 20,
- message: '密码为3~20位非空字符',
- trigger: 'blur'
- },
- {
- validator: checkUserName,
- trigger: 'blur'
- },
- ],
- })
正则表达式:
- //定义手机号校验规则
- const checkEmail = (_rule: any, value: string, callback: (arg0: Error | undefined) => void) => {
- const regEmail = /^1[3-9]\d{9}$/;
- if (value === '') {
- callback(new Error("输入不能为空"))
- } else if (regEmail.test(value)) {
- return callback();
- }
- callback(new Error("请输入正确手机号"));
- }
- //密码效验规则
- const checkUserName = (_rule: any, value: string, callback: (arg0: Error | undefined) => void) => {
- if (value.trim() === '') {
- callback(new Error("密码不可为空"))
- } else {
- return callback();
- }
- }