// Filename: newProductValidation.js
const newProductValidation = (req, res, next) => {
const { name, desc, price, imageUrl } = req.body;
const errors = [];
if (!name || name.trim() == '') {
errors.push("Name is required");
}
if (!price || parseFloat(price) < 1) {
errors.push("Price must be positive");
}
try {
const validUrl = new URL(imageUrl);
} catch (err) {
errors.push("URL is invalid");
}
if (errors.length > 0) {
return res.render('new-product', { errorMessage: errors[0] });
}
next();
};
export default newProductValidation;
// Filename: expressValidation.js
import { body, validationResult } from 'express-validator';
const expressValidation = async (req, res, next) => {
// Setup validation rules
const rules = [
body('name').notEmpty().withMessage("Name is required"),
body('price').isFloat({ gt: 0 }).withMessage("Price should be a positive value"),
body('imageUrl').custom((value, { req }) => {
if (!req.file) {
throw new Error('Image is required');
}
return true;
})
];
// Run validation rules
await Promise.all(rules.map(rule => rule.run(req)));
// Check for errors
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.render('new-product', { errorMessage: validationErrors.array()[0].msg });
}
next();
};
export default expressValidation;