目 录CONTENT

文章目录

el-form 使用方法整理

Jacky
2024-09-04 / 0 评论 / 0 点赞 / 63 阅读 / 3286 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-12-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

el-form 基础验证和自定义验证

<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="名称" prop="Name"> <el-input v-model="ruleForm.Name" style="width: 100%"></el-input></el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item :label="收件人" prop="Email">
            <el-input v-model="ruleForm.Email" style="width: 100%" placeholder="支持多个邮箱地址,用逗号分隔"></el-input> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
    <el-button type="primary" v-on:click="submit">submit</el-button>
  </div>
</template>
  <script>
export default {
  name: "",
  data() {
    return {
      ruleForm: {
        Name: "",
        Email: "",
      },
      rules: {
        //trigger 常用blur/change 可参考jquery的监听事件 支持数组  trigger: ["blur", "change"]
        Name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        Email: [
          { required: true, message: "请输入收件人", trigger: "blur" }, //非空验证
          { validator: this.validateEmails, trigger: "blur" }, //自定义验证
        ],
      },
    };
  },
  created() {},
  methods: {
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          console.log("验证通过");
        } else {
          console.log("验证不通过");
        }
      });
    },
    validateEmails(rule, value, callback) {
      const emails = value.split(",").map((email) => email.trim());
      const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
      for (let email of emails) {
        if (!emailPattern.test(email)) {
          return callback(new Error(`无效的邮箱地址: ${email}`));
        }
      }
      callback();
    },
  },
  mounted() {},
};
</script>
  
  <style>
</style>
  

el-form 清空验证

this.$refs.form.clearValidate();//注意,如果使用的时候不生效,可使用nextTick

el-form 重置并清空

this.$refs.form.resetFields(); 

el-form 自定义验证并触发vue的validate验证

      let message= "";
      let state= "success";
      if (hasOwner.length == 0) {
        message= "is required";
        state = "error";
      }
      this.form.forEach((element, index) => {
        this.$refs.refFormDetail.fields.find((field) => field.prop === `breakdownRule.${index}.owner`).validateMessage = message;
        this.$refs.refFormDetail.fields.find((field) => field.prop === `breakdownRule.${index}.owner`).validateState = state;
      });

0

评论区