javascriptnode.jsexpressmulterexpress-validator

Express-validator checking field in cookies instead of body


I have the following validator:

const validationSchema = checkSchema({
    'applicant.name': {
        exists: true,
        errorMessage: 'Name field is required',
    },
});

and the beginning of the following route (the rest is irrelevant):

userGeneralApplicant.post("/application/apply",
    upload.single('cv'),
    validationSchema,
    (req, res, next) => {

Data coming from the form is saved in req.body.applicant so inside of applicant there should be a property name. When the user doesn't insert a name then the applicant is just an empty object.

However, validation is retuning the following error whether there is a name value or not:

errors: [
    {
      type: 'field',
      value: undefined,
      msg: 'Name field is required',
      path: 'applicant.name',
      location: 'cookies'
    }
  ]

What should I do about it? Because I'm sure that I should call multer before the validation.


Solution

  • Below is the schema that is being used

    const validationSchema = checkSchema({
    'applicant.name': {
        exists: true,
        errorMessage: 'Name field is required',
    },
    

    });

    In the Implementation section, you are using the above-defined schema in the POST API. This does not look wrong for me logically.

    But, since which part of the request location the above schema should be validated has not been defined. It will check for all the locations

    body, cookies, headers, params and query
    

    As a solution, I think you need to add the default locations where the schema should look for. Since the data will be available in the request body. Below code should be valid. This code tells the schema to look for the request body by default.

    checkSchema(schema, ['body']);
    

    Or much better way of implementations could be using in operator. This tell the schema where to look for the data. Since it is an array, we can define multiple locations as well

    checkSchema({
     field: {
       in: ['body'],
       exists: true,
     },
    });
    

    For more details, you can check the below reference. It contains the written documentation with other options.

    Reference: Link