Search code examples
node.jsexpressexpress-validator

express-validator isDate and isISO8601 are always false


I'm trying to validate a date. I have tried everything I can but I have not found a solution. Input {"dob": "2002-10-02"}

'use strict'

var validator = require('validator');
var controller = {

    create: (req,res) =>{

        //pick parameters
        var parameters =  req.body;
     
        //validator
        
        try {
        
            //not working (always returns false)
            //var validate_dob = validator.isDate(parameters.dob + '');
            //also not working (always returns false)
            //var validate_dob = validator.isISO8601(parameters.dob + '');

            

        } catch (error) {
            
            return res.status(400).send({
                message: error
            });
        }
      }
}

Solution

  • In your question you mention tag express-validator, but in your middleware you use pure validator.

    Here I am putting an example using the express-validator lib (version 6.6.0). To use validate body parameters (login and password). But you can get the idea and pick the validation for your date from the validators list. Reference.

    server/validators/login.validator.js

    const { body, validationResult } = require('express-validator');
    
    exports.validationBodyRules = [
        body('login', 'login is required').exists(),
        body('password', 'password is required').exists(),
        body('login', 'login is required').notEmpty(),
        body('password', 'password is required').notEmpty()
    ];
    
    exports.checkRules = (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    };
    

    Here is the routes file

    server/routes/login.route.js

    const router = require('express').Router();
    const loginService = require('../controllers/login.controller');
    const loginValidator = require('../validators/login.validator');
    
    router.post('/login', loginValidator.validationBodyRules, loginValidator.checkRules, loginService.hashPassword, loginService.lookupLogin, loginService.logEmployee);
    
    module.exports = router;
    

    server/controllers/login.controller.js

    const postgres = require('../../lib/postgres');
    const jwt = require('jsonwebtoken');
    const crypto = require('crypto');
    
    exports.logEmployee = (req, res) => {
        res.status(200).json({ token: 'Bearer ' + jwt.sign(req.employee, process.env.SECRET, { expiresIn: 1800 }) });//expires in 1800 seconds
        res.end();
    };
    
    exports.hashPassword = (req, res, next) => {
        crypto.scrypt(req.body.password.toString(), 'salt', 256, (err, derivedKey) => {
            if (err) {
                return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not do login', param: req.params.id }] });
            }
            req.body.kdfResult = derivedKey.toString('hex');
            next();
        });
    };
    
    exports.lookupLogin = (req, res, next) => {
        const sql = 'SELECT e.employee_id, e.login FROM employee e WHERE e.login=$1 AND e.password = $2';
        postgres.query(sql, [req.body.login, req.body.kdfResult], (err, result) => {
            if (err) {
                return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not do login', param: req.params.id }] });
            }
            if (result.rows.length === 0) {
                return res.status(404).json({ errors: [{ location: req.path, msg: 'User or password does not match', param: req.params.id }] });
            }
            req.employee = result.rows[0];
            next();
        });
    };
    

    But you can use the ideas here to use a date validator.

    If you need a more complete example, please, let me know.