Reputation: 325
I have a simple form that needs validation for user inputs. If the input is too long, I want to show an error: "Entered value is too long. Max value is {{max}}.". How can I pass the max value to the error-string inside my dictionary.js file? This file contains all the strings I use in the form.
In the validator.js file, I loop the text fields that have a value and if it exceeds the max, I collect the error message to an array. The error message then shows below the specific field.
The solution below does not work, and it shows a text "[Object object]" below the text field. Any ideas?
dictionary.js
const eng = Object.freeze({
errors: {
invalidLength: 'Entered value is too long. Max value is {{max}}.',
required: 'Mandatory info is missing'
},
...
...
validator.js
const validate = (values) => {
const errors = {};
values.forEach(key => {
const value = key.value;
const max = key.max;
if (value.length > max) {
errors[key.field] = ('errors.invalidLength', {max});
}
}
});
return errors;
}
Upvotes: 1
Views: 143
Reputation: 11
You can try updating
const eng = Object.freeze({
errors: {
invalidLength: 'Entered value is too long. Max value is {{max}}.',
required: 'Mandatory info is missing'
}
to
const eng = Object.freeze({
errors: {
invalidLength: `Entered value is too long. Max value is ${max}.`,
required: 'Mandatory info is missing'
}
And,
if (value.length > max) {
errors[key.field] = ('errors.invalidLength', {max});
}
to
if (value.length > max) {
errors[key.field] = eng.errors.invalidLength;
}
Upvotes: 0
Reputation: 375
You could transform your errors object to the following:
dictionary.js
const eng = Object.freeze({
errors: {
invalidLength: (maxValue) => `Entered value is too long. Max value is ${maxValue}.`,
required: 'Mandatory info is missing'
}
})
Then in your validator: validator.js
if (value.length > max) {
errors[key.field] = eng.errors.invalidLength(max);
}
Upvotes: 1