1

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;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
willberthos
  • 305
  • 1
  • 4
  • 15
  • Try using `JSON.stringify()`. Have a look at this [issue](https://stackoverflow.com/questions/4750225/what-does-object-object-mean). – JnsBne Aug 30 '22 at 07:54
  • you can use `replace`. `errors[key.field] = eng.errors.invalidLength.replace('{{max}}', max)` – hawks Aug 30 '22 at 07:57

2 Answers2

1

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);
}

  • This one gives me "Uncaught TypeError: errors.invalidLength is not a function". I don't know if I should import the eng-const to validator.js or export the function invalidLength or something like that? – willberthos Aug 30 '22 at 09:22
  • You should import the object ```eng```. Then you can call ```eng.errors.invalidLength(maxValue)``` – victorperezpiqueras Aug 30 '22 at 09:44
0

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;
            }
ssdev
  • 11
  • 2