0

I am trying to write a custom Vuelidate rule to ensure a specified field is a date value after another field value.

Here's what I've written so far:

export const isDateAfter: (field: string | ((vm: any, parentVm?: Vue) => any)) => ValidationRule = (field) => {
  return helpers.withParams(
    {type: "isDateAfter", message: "{{fieldName}} must be after {{min}}", min: field},
    (value: Date, vm: any) => {
      const fieldValue = helpers.ref(field, vm, ??? );
      return isAfter(fieldValue, value);
    }
  )
}

My issue is what to pass to the third parameter of helpers.ref. All the JavaScript examples show the arguments as (field, this, vm), but I can't pass this in as I get the following warning:

TS7041: The containing arrow function captures the global value of 'this'.

How can I use the ref function properly?

James Hyde
  • 686
  • 1
  • 9
  • 25

1 Answers1

0

I solved this by creating my own ref function outside of Vuelidate:


const ref: (reference: string | ((vm: any) => any), vm: any) => any = (reference, vm) => {
  return typeof reference === "function" ? reference(vm) : vm[reference];
};

This is used inside a custom validation rule as such:

(value: Date, vm: any) => {
  const fieldValue = ref(field, vm);
  return isAfter(value, fieldValue);
}

and used in the form validators object as such:

isDateAfter: isDateAfter((vm) => vm.startDate)
James Hyde
  • 686
  • 1
  • 9
  • 25