Search code examples
validationexpress-validator

How to validate regex using express-validator?


I'm trying to validate a mobile number regex using express-validator.

I have browsed through the docs api but couldn't find the validator function that checks a regex. Will using regex.test() like the following work?


body('mobile', 'Invalid mobile number.')
           .escape()
           .exists({checkFalsy: true})
           .isLength({min: 11, max:11})
           .regex.test(/^(\+123)\d{11}$/)

Solution

  • I found .matches() validator function in express-validator which is the equivalent of regex.test().

    body('mobile', 'Invalid mobile number.')
    .escape()
    .exists({checkFalsy: true})
    .isLength({min: 11, max:11})
    .matches(/^(09|\+639)\d{9}$/)