margherita pizza
margherita pizza

Reputation: 7145

Vue js vuelidate cannot read custom validation inside the dynamic validation schema

enter image description here

I have this UI. If user check the All dates it will set the Boolean variable is_all_dates to true.So that means user don't care a date range he/she wants all the data without filter it by a date range.

On the other hand if user doesn't check the All dates I need to validate 3 things.

  1. He/she enter a from date (required)
  2. He/she enter a to date (required)
  3. From date < To date (custom validator)

For achieve this requirement I use dynamic validation schema.

I only need validate if All dates is equals to false. otherwise I don't need validations at all.

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

I declare my date_greather_than validation like this.

<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>

But the problem is I got an error

TypeError: Cannot read property 'date_greather_than' of undefined

My custom validator is not recognize inside the validations() function

I can use the keyword this like this. It's syntax error.

to: {
                  required,
                  this.date_greather_than
                }

Upvotes: 1

Views: 3532

Answers (1)

margherita pizza
margherita pizza

Reputation: 7145

I found the answer. The problem here was I only specify the if part only. By specifying both if part and else part my code works as expected.

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

Upvotes: 2

Related Questions