expressvalidationexpress-validator

Express Validator to validate time


I want to validate Time like this 18:14 with express-validator. When i used isTime as stated in validator like this body("StartTime").isTime().withMessage("Value must be time with HH:MM format") throwing an error isTime is not a function.

Is there any other approach to achieve Time validation.


Solution

  • Have you tried Regex?

    const { body, validationResult } = require('express-validator');
    
    body('StartTime')
      .custom((value) => {
        if (!/^([01]\d|2[0-3]):([0-5]\d)$/.test(value)) {
          throw new Error('Value must be time with HH:MM format');
        }
        return true;
      })
    

    Here is the link to see how to use the regex patterns for date formats.