vue3 + element plus 自定义验证规则(两个表单必填其中一个)

element plus 表单

vue3 + element plus 自定义验证规则(两个表单必填其中一个)_第1张图片

// 自定义验证规则
  const validateCustom = (rule: any, value: any, callback: any) => {
    if (!contactsForm.value.mobile && !contactsForm.value.email) {
      callback(new Error('电话和邮箱至少必填其中一个'));
    } else {
      if (contactsForm.value.mobile || contactsForm.value.email) {
        if (rule.field === 'mobile') {
          if (contactsForm.value.mobile) {
            if (!Regexps.phone.test(contactsForm.value.mobile as string)) {
              callback(new Error('电话错误'));
            }
            ruleFormRef.value?.clearValidate(['email']);
            callback();
          }
        }
        if (rule.field === 'email') {
          if (contactsForm.value.email) {
            if (!Regexps.email.test(contactsForm.value.email)) {
              callback(new Error('邮箱错误'));
            }
            ruleFormRef.value?.clearValidate(['mobile']);
            callback();
          }
        }
        callback();
      }
    }
  };


 const rules = reactive<FormRules>({
    name: [{ required: true, message: '请完善', trigger: ['blur', 'change'] }],
    mobile: [{ validator: validateCustom, trigger: ['blur', 'change'], required: true }],
    email: [{ validator: validateCustom, trigger: ['blur', 'change'], required: true }],
 
  });

你可能感兴趣的:(#,element,plus,vue,vue.js)