Reputation: 353
I have two fields: login and password. I use custom validators to validate:
login: {
isNotNull: { errorMessage: 'Required field' },
isServiceUser: {
errorMessage: 'Failed to login',
options: req.body.password,
},
},
password: {
isNotEmpty: { errorMessage: 'Required field' },
}
isServiceUser validates by making http request to another service. How can I validate them both at once and send to client that both fields are invalid?
Upvotes: 2
Views: 6115
Reputation: 21
It can be implemented this way:
body(['login', 'password']).custom((value) => { // your logic here });
callback provided to custom method will be called two times for each field (login and password)
Upvotes: 1
Reputation: 123
You can use custom validation.
Assume you want to check password if exist and user name:
const { check, validationResult } = require('express-validator/check')
app.post(upload.single('customerImage'),[
check('name').custom(async (name, {req}) => {
// api request for fetching user name
const res = await getCust(name)
// change if condition to make it do what you want
if(!res && req.body.password === ""){
throw new Error('user name or password invalid')
}
})], (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.status(442).json({ errors: errors.array() })
}
//do something
})
You have to change the validation condition as you like.
If you want to use Schema Validation
Upvotes: 2