I have created a validate that for validate every data before create, but i am not sure that my validator works. So, i would like to ask for help about this and i hope community can help me to improve my validator. I would like to receive your feedback and suggestions, if there's something wrong please tell me
// car.validator.js
import { body } from "express-validator";
export var validateCar = () => {
var regex = /^[A-Za-z0-9 ] $/;
var valid = regex.test(req.body.name);
if (!req.body.name && !valid) {
res.status(400).send({
message: "Name can not be empty or not contains special characters",
});
return;
} else if (!req.body.color) {
res.status(400).send({
message: "Color can not be empty!",
});
return;
} else if (!req.body.brand) {
res.status(400).send({
message: "Brand can not be empty!",
});
return;
}
};
CodePudding user response:
Simplest way to use express-validator
with node js is:
Suppose I assume you are using /cars/create
endpoint to send POST request which creates entry of car in your db then in your route file should be:
const { check } = require("express-validator");
router.post(
"/cars/create",
[
check('name')
.escape()
.notEmpty()
.matches(/^[A-Za-z0-9 ] $/),
check("color").notEmpty(),
check("brand").notEmpty(),
],
carsController.createCar
);
In your carsController.createCar you will have array of errors if validation is failed:
const { validationResult } = require("express-validator");
const createCar = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()){
return res
.status(200)
.json({ err: "Invalid Data Passed!", errors: errors });
}
// code to be implemented if validation is passed
}
check this doc for more details and your requirements.
CodePudding user response:
//car.validator.js
import { check } from "express-validator";
export var validateCar = () => {
var validate = [
check("name")
.escape()
.notEmpty()
.matches(/^[A-Za-z0-9 ] $/),
check("color").notEmpty(),
check("brand").notEmpty(),
];
return validate;
};
Car Controller:
import { validationResult } from "express-validator";
// create new car
export async function createCar(req, res) {
const car = new Car({
car_id: id,
name: req.body.name,
color: req.body.color,
brand: req.body.brand,
});
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res
.status(200)
.json({ err: "Invalid Data Passed!", errors: errors });
}
try {
let newCar = await car.save();
return res.status(201).json({
success: true,
message: "New course created successfully",
Car: newCar,
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "Server error. Please try again.",
error: error.message,
});
}
}