0
votes

I have a custom veevalidate rule that I use to see if the value entered is already in an array in that component. I want to use this rule in different components with different arrays. Is there a way to do this? Here is my current rule in just one component

const isUnique = (value) => {
      const reg = new RegExp(`^${value}$`, 'i');
      const inputValue = this.myArray.filter(str => reg.test(str));

      if (inputValue.length > 0) {
        return {
          valid: false,
          data: {
            message: `The ${inputValue}  already exists.`,
          },
        };
      }
      return { valid: true };
    };

    Validator.extend('unique', {
      validate: isUnique,
      getMessage: (field, params, data) => data.message,
    });
1

1 Answers

0
votes

You sure can - either you can use the existing rule called oneOf which is documented here, or you can change your rule to accept parameters. It looks like your rule is case-insensitive, so probably you'd want to stick with that. All you would need to do is accept a 2nd parameter to your isUnique function and then use that instead of this.myArray:

const isUnique = (value, values) => {
      const reg = new RegExp(`^${value}$`, 'i');
      const inputValue = values.filter(str => reg.test(str));

Then in your template, you would call it like this:

<ValidationProvider :rules="{isUnique:myArray}">