【问题标题】:How to add an error message using HTML 5 Validation with Vue如何使用带有 Vue 的 HTML 5 验证添加错误消息
【发布时间】:2021-05-17 07:34:05
【问题描述】:

我遵循了一个关于使用 Vue.js 进行 HTML 5 表单验证的精彩教程,我尝试了太多次在失败的输入旁边添加消息错误,但我做不到。 这是教程:https://logaretm.com/blog/2019-05-03-html-aided-vuejs-form-validation/

这是我的代码:

function updateMessage(el, vm) {
  vm.errors = Object.assign({}, vm.errors, {
    [el.name]: el.validationMessage
  });
}

export const ValidateMixin = {
  data: () => ({
    errors: {}
  }),
  computed: {
    hasErrors() {
      // Check if we have errors.
      return Object.keys(this.errors).some(key => {
        console.log(this.errors)
        return !!this.errors[key];
      });
    }
  },
  directives: {
    validate: {
      bind(el, _, vnode) {
        const vm = vnode.context;
        el.addEventListener("input", e => {
          updateMessage(e.target, vm);
        });
        vnode.context.$on("validate", () => {
          updateMessage(el, vm);
        });
      }
    }
  },
  methods: {
    validate() {
      this.$emit("validate");
    }
  }
};

我想在每个输入字段旁边的 span 中显示错误消息

【问题讨论】:

    标签: javascript vue.js validation vue-component vue-mixin


    【解决方案1】:

    mixin 的 errors 对象属性包含元素 name 到该元素的验证错误消息的映射。例如,在<input name="myEmail" type="email" v-validate> 的输入中输入无效的电子邮件地址会在errors.myEmail 中创建一条验证消息。

    您可以使用模板中的errors 对象将元素的错误消息绑定到对应的input 旁边的span

    <input name="myEmail" type="email" v-validate>
    <span v-if="errors.myEmail">{{ errors.myEmail }}</span>
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多