Search code examples
javascriptvue.jsvalidationvuejs2vuelidate

Vuelidate check 1 rule only


I have a huge input form which is needed to be populated with data and be able to save progress, to finish the form later, BUT only when the form fits 1 custom rule only:

  • form is able to be saved when it not containing any forbidden words(let's say that forbidden words are [TEST1, TEST2])

That means that is for example I have validations rules like this:

validations: {
  A: {
    required,
    $each: {
      Aa: { required },
      Ab: { required, dontHaveForbiddenWords },
      Ac: { required, dontHaveForbiddenWords }
    },
  },
  B: {
    required,
    Ba: { required, dontHaveForbiddenWords },
    Bb: { required },
  }
  // ... a lot of additional fields
}

In this case, I want the form to be able to be saved when all fields are empty(cos it DO NOT CONTAIN forbidden words) even if it has unfilled required fields.

The problem is that the form has an $invalid state due to required rule, and I have no idea how to bypass it.


Solution

  • The working solution was to use JSON.stringify()

    My team mate it to stringify validationState, and test it on a regex string that contains name of our validationRule, which in my case is dontHaveForbiddenWords, and check for a false value, that means that at least 1 rule is failed on entire form:

    hasForbiddenCharacters() {
      const validationStateString = JSON.stringify(this.$v.currentOffer, null, 0)
      const hasForbiddenCharacters = /\"dontHaveForbiddenWords\":false/.test(validationStateString)
    
      return hasForbiddenCharacters;
    }