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.
2
Answers
multer is not involved here as it performs all its operation against the file and enable in-memory file storage.
Use
check()
– as it is dedicated to validating all request components and has support for validation rule chaining, You are usingcheckSchema()
which validates against the provided schema so It might not be providing expected outputBelow is the schema that is being used
});
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
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.
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 wellFor more details, you can check the below reference. It contains the written documentation with other options.
Reference: Link