Hirdesh Singh
Hirdesh Singh

Reputation: 23

How to validate array of objects in express validator

         text_settings_descriptions: {
    'en': { language_id: '5a3a13238481824b077b23ca', value: '' },
    'ar': { language_id: '600eca59ced1c8317d473b54', value: '' }
  }

this is my address array

 app.post(
  '/addresses',
  check('text_settings_descriptions.*.value'),
 
  (req, res) => {
    // Handle the request
  },
);

And I am using this validation it validates both language's value. But I want it validates only 'en' language value

Upvotes: 1

Views: 2221

Answers (1)

eol
eol

Reputation: 24555

If you want to make sure that the value inside en is not empty, you can use the following:

const {check, validationResult} = require('express-validator');

app.post(
    '/addresses',
    check('text_settings_descriptions.en.value').notEmpty(),
    (req, res) => {
        const errors = validationResult(req);
        console.log(errors);
        // ... handle errors and request
    },
);

With above code if the value was an empty value, the follwoing will be logged to the console:

 {
  formatter: [Function: formatter],
  errors: [
    {
      value: '',
      msg: 'Invalid value',
      param: 'text_settings_descriptions.en.value',
      location: 'body'
    }
  ]
}

Upvotes: 1

Related Questions