a-from 自定义规则使用,及初始默认值规则校验失效问题
- 自定义规则使用,下面以修改密码为例
<template> <a-form ref="formRef" :model="userPassword" style="height: 243px" :label-col="{ style: { width: '100px' } }" :rules="rules" label-width="80px" > <a-form-item label="原密码" name="originalPassword">//name在我们使用规则校验时,这个字段必填,用来对应个字段规则的判定 <a-input-password v-model:value="userPassword.originalPassword" placeholder="请输入原密码" type="password" show-password /> </a-form-item> <a-form-item label="新密码" name="newPassword"> <a-input-password v-model:value="userPassword.newPassword" placeholder="请输入新密码" type="password" show-password /> </a-form-item> <a-form-item label="确认密码" name="confirmPassword"> <a-input-password v-model:value="userPassword.confirmPassword" placeholder="请确认密码" type="password" show-password /> </a-form-item> </a-form> </template> <script lang="ts" setup> import { ref, reactive } from "vue"; import { CloseOutlined, CheckOutlined } from "@ant-design/icons-vue"; import { notification } from "ant-design-vue"; import { RuleObject } from "ant-design-vue/es/form/interface"; const Passwordvisible=ref(false); const formRef = ref(); const userPassword = reactive({ originalPassword: "", newPassword: "", confirmPassword: "", }); //新密码判定 let validatePass = async (rule: RuleObject, value: string) => { const reg = /^[\u4e00-\u9fa5]+$/; if (value === "") { return Promise.reject("新密码不能为空!"); } else if (reg.test(value)) { return Promise.reject("密码中不能出现汉字"); } else { if (userPassword.confirmPassword !== "") { formRef.value.validateFields("confirmPassword"); } return Promise.resolve(); } }; //确认密码判定 let validatePass2 = async (rule: RuleObject, value: string) => { const reg = /^[\u4e00-\u9fa5]+$/; if (value === "") {//校验是否为空,我们在写自定义规则的时候,就可以把其他的,比如必填判定等,都可以写进一个方法了 return Promise.reject("二次密码不能为空!");//reject报出警告 } else if (reg.test(value)) { return Promise.reject("密码中不能出现汉字"); } else if (value !== userPassword.newPassword) { return Promise.reject("两次输入密码不一致!"); } else { return Promise.resolve();//resolve验证通过 } }; const rules = { originalPassword: [ { required: true, message: "原密码不能为空", trigger: "blur" }, ], newPassword: [{ required: true, validator: validatePass, trigger: "blur" }],//validator为自定义校验,后面写自己需要的校验方法即可 confirmPassword: [ { required: true, validator: validatePass2, trigger: "blur" }, ], }; const emit = defineEmits<{ (event: "cancel", data: any): void; }>(); const cancel = () => { emit("cancel", { type: "cancel" }); };
//进行规则校验 const submit = () => { formRef.value .validate() .then(() => { passwordSubmit(); }) .catch(() => {}); }; //修改密码 const passwordSubmit = () => { notification.success({ message: "密码修改成功", }); }; </script> -
初始默认值,无法校验,明明存在默认值却一直警告未输入。
这个原因:
(1.)可以看下a-form绑定的:model="userPassword"是否和自己所要判定的值,比如a-input中的v-model:value="userPassword.originalPassword"一致,如果一致,就进行第二步,如果不一致,改后试下看看好了没,还是报未输入就进行第二步。
(2.)将规则校验中{ required: true, message: "原密码不能为空", trigger: "blur" }的trigger删除,再试下,应该就好了。
目前我就遇到了这两种情况。