Skip to content

Instantly share code, notes, and snippets.

@vivekyadav5750
Last active January 23, 2024 05:43
Show Gist options
  • Save vivekyadav5750/a6de732058cef88d1b50c0f163f94317 to your computer and use it in GitHub Desktop.
Save vivekyadav5750/a6de732058cef88d1b50c0f163f94317 to your computer and use it in GitHub Desktop.
Nodejs Validation

Node.js Validation

1. Own Validation

// 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;

2. Express Validation

// 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment