【问题标题】:Vue js vuelidate cannot read custom validation inside the dynamic validation schemaVue js vuelidate 无法读取动态验证模式中的自定义验证
【发布时间】:2018-11-11 14:37:26
【问题描述】:

我有这个用户界面。如果用户检查All dates,它会将布尔变量is_all_dates 设置为true。这意味着用户不关心日期范围,他/她想要所有数据而不按日期范围过滤。

另一方面,如果用户不检查 All dates 我需要验证 3 件事。

  1. 他/她输入起始日期(必填
  2. 他/她输入一个日期(必填
  3. 从日期 自定义验证器)

为了达到这个要求,我使用了动态验证模式。

我只需要验证All dates 是否等于假。否则我根本不需要验证。

validations() {
        if (!this.is_all_dates) {
          return {
            from: {
              required
            },
            to: {
              required,
              date_greather_than
            }
          };
        }
      },

我这样声明我的date_greather_than 验证。

<script>
    const date_greather_than = (value, vm) => {
      let from = new Date(vm.from);
      let to = new Date(value);
      return from < to;
    };
    export defaults:{
        validations(){},
        data(){return{}}
    }
</script>

但问题是我遇到了错误

TypeError:无法读取未定义的属性“date_greather_than”

我的自定义验证器在 validations() 函数中无法识别

我可以像这样使用关键字this。这是语法错误。

to: {
                  required,
                  this.date_greather_than
                }

【问题讨论】:

  • code 你提供了包含那个的全部代码吗?
  • @BoussadjraBrahim 你是什么意思?
  • 代码类似于 App.vue 在这个例子中 codesandbox.io/s/w2n99onq78
  • @BoussadjraBrahim 我还有另一个名为is_all_dates 的布尔变量。如果is_all_dates == false 那么只有我需要发生这种情况。当我使用 if 语句时,问题就来了。
  • @BoussadjraBrahim 我更新了我的问题。

标签: vue.js vuejs2 vuelidate


【解决方案1】:

我找到了答案。这里的问题是我只指定了 if 部分。通过同时指定 if 部分和 else 部分,我的代码按预期工作。

validations() {
    if (this.is_limit_by_range) {
      return {
        to: { required, date_greather_than },
        from: { required },
        status: { required }
      };
    } else {
      return {
        status: { required }
      };
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多