0
votes

I have a custom rule to check if a name is unique, the textfield exists multiple times in my form, because the the form is repeatable

I have done a small simplyfied demo there -> https://codesandbox.io/s/v81mxn2ojy take a look in the console to see that the validation gets multiple times called if I write inside the textfields. It stacks if I switch between the textfields and change the value.

template

<p class="sizes__input" v-for="(size, i) in sizes">
  <span>Size: </span>
  <input
    type="text"
    :name="`prefix${i}`"
    class="textfield max-dim__input"
    v-model="size.prefix"
    maxlength="8"
    autocomplete="off"
    v-validate="{ required: true, unique: prefixes }"
    :class="{ error: errors.has(`prefix${i}`) }"
  />
</p>

script

data() {
    return {
      sizes: [
        { prefix: "xl_", width: "1400", height: "1400" },
        { prefix: "l_", width: "1100", height: "1100" },
        { prefix: "m_", width: "800", height: "800" },
        { prefix: "s_", width: "600", height: "600" },
        { prefix: "thumb_", width: "200", height: "200" }
      ]
    };
  },
  computed: {
    prefixes() {
      console.log("prefix");
      if (this.sizes) {
        return this.sizes.map(item => {
          return item.prefix;
        });
      }
    }
  }

rule

const unique = {
  getMessage(field) {
    return `Such ${field} already exists.`;
  },
  validate(value, args) {
    if (value) {
      console.log(value, args, args.indexOf(value));
      return args.indexOf(value) === -1;
    }
    return false;
  }
};

Validator.extend("unique", unique, {
  immediate: false
});

ok found a solution On focus I filter the data and send this to my validator.

inputfield

<input
    v-validate="{ required: true, unique: filteredSizes }"
    @focus="filterSizes(i);"

added filteredSizes

data() {
  return {
    filteredSizes: [],
    sizes: 

on focus

filterSizes(i) {
  const otherSizes = [...this.sizes];
  otherSizes.splice(i, 1);
  this.filteredSizes = otherSizes.map(item => {
    return item.prefix;
  });
}

https://codesandbox.io/s/38qyyymyw5

1

1 Answers

0
votes

I believe it may be this.

You need use blur behavior. There are alternative events that might give you the same behavior of blur using data-vv-validate-on attribute to override the default events.

Examples:

For the multiselect it emits close event when the dropdown is closed which is also when the user leaves the control.

<multiselect data-vv-validate-on="input|close" ...>

For the date-picker you can instead validate on closed since that event emits when the user leaves the control.

<datepicker data-vv-validate-on="input|closed" ...>

VeeValidate Doc

I hope this help.