vue3+element-plus的表单验证

表单验证

基本验证

<el-form :model="ruleForm" :rules="rules" ref="addRuleForm" label-position="top">
        <el-form-item label="公司名称" prop="name">
          <el-input placeholder="请输入" v-model="ruleForm.name">el-input>
        el-form-item>
        <el-form-item>
          <el-button @click="submitForm">提交el-button>
          <el-button @click="resetForm">重置el-button>
        el-form-item>
el-form>
<script>
import { reactive, toRefs, ref, unref } from "vue";
export default {
  setup() {
    const state = reactive({
      ruleForm: {
        name: "",
        seletValue: "1",
      },
      rules: {
        name: [{ required: true, message: "ddd", trigger: "blur" }],
      },
    });
    // addRuleForm 使用ref
    const addRuleForm = ref();
    // submit
    const submitForm = async () => {
      // addRuleForm 使用unref
      const form = unref(addRuleForm);
      if (!form) {
        return;
      }
      try {
        await form.validate();
        console.log("验证成功");
      } catch (err) {
        console.log("err===" + err);
      }
    };
    // reset
    const resetForm = () => {
      const form = unref(addRuleForm);
      form.resetFields();
    };
    return {
      ...toRefs(state),
      addRuleForm,
      submitForm,
      resetForm,
    };
  },
};
</script>

自定义验证

//只需要修改 rules
const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input the name'))
      } else {
        if (state.ruleForm.name !== 'admin') {
          callback(new Error('The name is admin'))
        }
        callback()
      }
    }
//ruleForm 规则
rules: {
        name: [{ validator: validateName, trigger: 'blur' }],
      },

vue3还有一种setup语法糖的写法,记录下免得自己搞忘了

<script setup>
// 通过defineProps指定当前props类型的同时,获得上下文的props对象
	import { defineProps, reactive, ref } from "vue";
	const form = reactive({
		name: '',
		radioCheck:false
	})
	//表单元素
	const ruleForm = ref(null);
	//表单验证 
	const rules = {
	  name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
	};
	//自定义表单验证
	/**
	 *const rules = {
	  age: [
	    {
	      required: true,
	      validator: (rule, value, callback) => {
	        const { radioCheck } = form;
	        callback(radioCheck ? "" : "请先阅读通知");
	      },
	      trigger: "blur",
	    },
	  ],
	};
 	 */
	const resetForm = () => {
	  console.log("reset form");
	};
	const submitForm = async () => {
	  try {
	    const form = unref(ruleForm);
	    await form.validate(); //使用unref(ruleForm)表单验证写法
	    // await ruleForm.value.validate(); //未使用unref 表单验证的写法
	    console.log("验证陈宫");
	  } catch (err) {
	    console.log("失败" + err);
	  }
	};
</script>

你可能感兴趣的:(笔记,vue3,前端,vue.js,javascript,elementui)