I have implemented joi validation for my project but it's not working for any single field. whatever you pass it's get stored in database it doesn't validate any field even though i did a code for validation Here is a code for validation
import * as Joi from "joi";
import { Request, Response, NextFunction } from 'express';
import { StatusCodes } from 'http-status-codes';
import { sendError } from "../responseHelper";
import { validationOptions } from "./_index";
export class CountryValidator {
public async createCountryValidator(req: Request, res: Response, next: NextFunction) {
try {
const schema = Joi.object({
id: Joi.number().required(),
name: Joi.string().required(),
code: Joi.string().required(),
status: Joi.number().valid(0, 1).required(),
});
schema.validate(req.body, validationOptions);
next();
} catch (error) {
sendError(res, error, error.code, StatusCodes.INTERNAL_SERVER_ERROR);
}
}
}
And this is my route path
adminRoute.route('/country/create')
.post(countryValidator.createCountryValidator, countryController.createCountry);
And on this path I'm posting below data is which totally wrong as per validation but still it accepts all the data and not throwing any validation error
{
"name":"BR1Z",
"code":100,
"status":"1"
}
Can any one help me to resolve this issue ?
schema.validate
returns object with error
filed (instead of throwing error).
...
const joiRes = schema.validate(req.body, validationOptions);
if(joiRes.error){
sendError(res, error, error.code, StatusCodes.INTERNAL_SERVER_ERROR);
}
...