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.
CodePudding user response:
UPDATE: This answer is not working, it was a fluke and bad testing from my side, the flag that I set up as the conditional check is NOT reapplied on this.$v.$touch()
and stays with a default value all the time
As @EstusFlask suggest I've created a custom validator so I could turn it off in some cases, it uses a top-level variable instead of a parameter because I want to overrule this validator for all fields at once, also in my project I have conditional required validators
, and I found not create a better solution, would be glad if you will edit my solution:
import { helpers } from 'vuelidate/lib/validators';
let isRequired = true;
const customRequiredValidator = (value) => {
return isRequired ? helpers.req(value) : true;
}
later in code, I have 2 handlers:
- onSave() where I am turning the
required
rule OFF - onSumbit() where I am setting the
required
rule back ON
smth like this
onSave() {
isRequired = false;
if (this.$v.$invalid) {
isRequired = true;
// show alert
return;
}
isRequired = true;
// save form progress
}
// isRequired is always true after onSave
onSubmit() {
this.$v.$touch(); // to trigger the validation
if (this.$v.$invalid) return; // show alert
// sumbit the form
}
CodePudding user response:
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;
}