express validator
// this method create custom express validator using middleware
const { validationResult, check } = require('express-validator')
exports.resultsValidator = (req) => {
const messages = []
if (!validationResult(req).isEmpty()) {
const errors = validationResult(req).array()
for (const i of errors) {
messages.push(i)
}
}
return messages
}
exports.registerValidator = () => {
return [
check('username')
.notEmpty()
.withMessage('username is required')
.not()
.custom((val) => /[^A-za-z0-9\s]/g.test(val))
.withMessage('Username not use uniq characters'),
check('password')
.notEmpty()
.withMessage('password is required')
.isLength({ min: 8 })
.withMessage('password must be 8 characters')
]
}
exports.loginValidator = () => {
return [
check('username').notEmpty().withMessage('username or email is required'),
check('password').notEmpty().withMessage('password is required')
]
}
// how to use express validator in controller for results message
const errors = resultsValidator(req)
if (errors.length > 0) {
return res.status(400).json({
method: req.method,
status: res.statusCode,
error: errors
})
}
// how to use express validator in route
route.post('/login', loginValidator(), (req, res) => {
return res.status(200).send('Login Sucessfuly');
});
route.post('/register', registerValidator(), (req, res) => {
return res.status(200).send('Register Sucessfuly');
});
4
2
const { check } = require('express-validator');
app.post(
'/user',
// ...some other validations...
check('password')
.isLength({ min: 5 })
.withMessage('must be at least 5 chars long')
.matches(/\d/)
.withMessage('must contain a number'),
(req, res) => {
// Handle the request somehow
},
);
Thank you!
2
0
3.75
9
import { Request } from 'express'
import { check, validationResult, ValidationError, ValidationChain, Result, Meta } from 'express-validator'
export const expressValidator = (req: Request): ValidationError[] => {
const errors: Result<ValidationError> = validationResult(req)
const messages: ValidationError[] = []
if (!errors.isEmpty()) {
for (const i of errors.array()) {
messages.push(i)
}
}
return messages
}
export const registerValidator = (): ValidationChain[] => [
check('firstName').notEmpty().withMessage('firstName is required'),
check('firstName')
.not()
.custom((val: string) => /[^a-zA-Z]/gi.test(val))
.withMessage('firstName cannot include unique character'),
check('lastName').notEmpty().withMessage('lastName is required'),
check('lastName')
.not()
.custom((val: string) => /[^a-zA-Z]/gi.test(val))
.withMessage('lastName cannot include unique character'),
check('email').notEmpty().withMessage('email is required'),
check('email').isEmail().withMessage('email is not valid'),
check('password').notEmpty().withMessage('password is required'),
check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters'),
check('location').notEmpty().withMessage('location is required'),
check('location')
.not()
.custom((val: string) => /[^a-zA-Z]/gi.test(val))
.withMessage('location cannot include unique character'),
check('phone').notEmpty().withMessage('phone is required'),
check('phone').isLength({ min: 10 }).withMessage('phone number must be at least 10 characters'),
check('phone').isLength({ max: 12 }).withMessage('phone number must be at least 12 characters'),
check('phone').isMobilePhone('id-ID').withMessage('phone number is not valid')
]
export const loginValidator = (): ValidationChain[] => [
check('email').notEmpty().withMessage('email is required'),
check('email').isEmail().withMessage('email is not valid'),
check('password').notEmpty().withMessage('pasword is required')
]
export const emailValidator = (): ValidationChain[] => [
check('email').notEmpty().withMessage('email is required'),
check('email').isEmail().withMessage('email is not valid')
]
export const tokenValidator = (): ValidationChain[] => [
check('token').notEmpty().withMessage('token is required'),
check('token').isBase64().withMessage('token is not valid')
]
export const passwordValidator = (): ValidationChain[] => [
check('password').notEmpty().withMessage('password is required'),
check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters'),
check('password')
.not()
.custom((value: string, { req }: Meta) => req.body.cpassword !== value)
.withMessage('confirm password is not match with password'),
check('cpassword').notEmpty().withMessage('cpassword is required'),
check('cpassword').isLength({ min: 8 }).withMessage('cpassword must be at least 8 characters')
]
Thank you!
9
0
4.43
7
npm install --save express-validator
Thank you!
7
0
3.4
5
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').isEmail(),
check('age').isNumeric()
], (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
Thank you!
5
0
3
2
npm install --save express-validator
Thank you!
2
0
Are there any code examples left?
New code examples in category TypeScript
-
TypeScript 2022-03-27 19:30:45 typescript promise
-
TypeScript 2022-03-27 17:25:44 how to search for imports in vscode
-
TypeScript 2022-03-27 17:15:20 angular formgroup mark as touched
-
TypeScript 2022-03-27 17:05:06 use of slice and splice add elements array
-
TypeScript 2022-03-27 16:50:23 android studio loop through all objects in layout
-
TypeScript 2022-03-27 14:35:08 wergensherts meaning
-
TypeScript 2022-03-27 13:50:15 remove all the elements from a numpy array python
-
TypeScript 2022-03-27 12:35:49 redux toolkit typescript install
-
TypeScript 2022-03-27 12:35:30 laravel middleware for apis