V-text-field
lastmod 2021-07-23created 2021-07-236 edits
Error Bucket
The part shown at the bottom, as below.
V-text-field-error-buckets.png
Methods
validate
The implementation is as follows:
validate (force = false, value?: any): boolean {
const errorBucket = []
value = value || this.internalValue
if (force) this.hasInput = this.hasFocused = true
for (let index = 0; index < this.rules.length; index++) {
const rule = this.rules[index]
const valid = typeof rule === 'function' ? rule(value) : rule
if (valid === false || typeof valid === 'string') {
errorBucket.push(valid || '')
} else if (typeof valid !== 'boolean') {
consoleError(`Rules should return a string or boolean, received '${typeof valid}' instead`, this)
}
}
this.errorBucket = errorBucket
this.valid = errorBucket.length === 0
return this.valid
},
How to call rules directly from code
Call the validate() function of v-text-field.
const V_TEXT_FIELD_VALIDATE = 'validate';
// ...
validateForms(): boolean {
const fields = [this.$refs.usernameField, this.$refs.passwordField];
let result = true;
for (const key in fields) {
const field = fields[key];
if (!field) {
continue;
}
const validate = field[V_TEXT_FIELD_VALIDATE];
if (validate === undefined) {
continue;
}
// You need to repeat the validation function for every field.
if (!validate(true)) {
result = false;
}
}
return result;
}
Troubleshooting
v-text-field errorBuckets not updating when the language changes
Once the #Error Bucket has been shown, changing the language with vue-i18n does not update it. In this case, check the validations value of v-text-field and call the validate() function again.
const V_TEXT_FIELD_VALIDATE = 'validate';
const V_TEXT_FIELD_VALIDATIONS = 'validations';
// ...
updateErrorBuckets() {
const fields = [this.$refs.usernameField, this.$refs.passwordField];
let result = true;
for (const key in fields) {
const field = fields[key];
if (!field) {
continue;
}
const validate = field[V_TEXT_FIELD_VALIDATE];
const validations = field[V_TEXT_FIELD_VALIDATIONS];
if (validate === undefined || validations === undefined) {
continue;
}
if (validations.length >= 1) {
validate(true);
}
}
return result;
}
// ...
}
See also
Pages that link here