i have create register form and i want to validate form. I am using express-validator middleware but i am able to validate. But if input type if valid value show still validation error message.
my module code is:
please help.
<pre>
const { body,sanitizeBody } = require('express-validator');
exports.registerform=[
body('fristName','Frist Name must be at least 2 chars long.').isLength({ min: 2 }),
body('lastName','Last name must be at least 2 chars long.').isLength({ min: 2 }),
body('email','must be a valid email.').isEmail(),
body('gender','please select gender.').isLength({ min: 2 }),
body('dob','Please provide date of birth.').isLength({ min: 2 }),
body('skills','Please any one skill.').isLength({ min: 2 }),
body('password','Password required').trim().notEmpty()
.isLength({ min: 5 }).withMessage('password must be minimum 5 length')
.matches(/(?=.*?[A-Z])/).withMessage('At least one Uppercase')
.matches(/(?=.*?[a-z])/).withMessage('At least one Lowercase')
.matches(/(?=.*?[0-9])/).withMessage('At least one Number')
.matches(/(?=.*?[#?!#$%^&*-])/).withMessage('At least one special character')
.not().matches(/^$|\s+/).withMessage('White space not allowed'),
body('confirm_password').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password Confirmation does not match password');
}
})
]
</pre>
error messages
this is problem resolved. I validate validation middleware after multer middleware.
thank you.
Related
I have a field that can have 0 or any number. If it has 0 I want to do a validation, if it doesn't then I want to do other. How can I do that? This was my attempt.
app.post("/admin/updskill", [
body('i_sCatEdit')
.notEmpty().withMessage('The category id can not be empty.').bail()
.isNumeric({ no_symbols: true }).bail()
.trim().escape(),
body('sz_sCatEdit')
.if(body('i_sCatEdit').equals(0))
.isEmpty().withMessage('The category name must be empty.').bail().escape(),
body('sz_sCatEdit')
.if(body('i_sCatEdit').not().equals(0))
.notEmpty().withMessage('The category name can not be empty.').bail()
.exists({ checkNull: true, checkFalsy: true }).withMessage('The category name must exist (eg: not undefined, null).').bail()
.isLength({ min: 3, max: 149 }).withMessage('The category name min length is 3 characters and the max 149.').bail().escape()
In case the above code is not clear enough, this is pseudo code
if(i_sCatEdit === 0){
validation1
} else{
validation2
}
case 'user_name': {
return [
check(
'content.data.userName',
'username need atleast one alphabet'
)
// .matches('(?=.[a-z])(?=.[0-9])')
.exists()
.trim()
.bail()
.isLength({ min: 6 })
.withMessage('User Name must be atleast have 6 characters')
.isLowercase()
.withMessage('Must be all small letters')
case 'user_name': {
return [
check(
'content.data.userName',
'username need atleast one alphabet'
)
// .matches('(?=.*[a-z])(?=.*[0-9])')
.exists()
.trim()
.bail()
.isLength({ min: 6 })
.withMessage('User Name must be atleast have 6 characters')
.isLowercase()
.withMessage('Must be all small letters')
This regular expression helps you to check the first character is alphabet or not.
^[a-zA-Z][\w\s-]+
First character can be only a-zA-Z
Not to allow special characters other than "space" and "hyphen(-)"
.matches(/^[a-zA-Z][\w\s-]+/)
Hope it works, Thank you!
I am using joi in a node project, and I would like to put the following rule : my field could be of length 6 or 8 (nothing else), I've tried to do the following but its not working :
Joi.object({
iban: Joi.string().alphanum().length(6).length(8)
})
The last written rules override the first one, so here I only accept value with length 8 and no more value with length 6
Thanks in advance
Try writing custom validator like this.
you can read more about custom validators here
Joi.object({
iban: Joi.string().alphanum().custom((value, helper) => {
if(value.length === 6 || value.length === 8){
return value;
} else {
return helper.message("iban must be 6 or 8 characters long")
}
});
})
``
this one is working well :
Joi.alternatives().try(Joi.string().alphanum().length(6), Joi.string().alphanum().length(8))
When I use the express-validator and validate fields, I always get the error response with value, msg, param and location properties. What if I want to add extra properties in there like say code to communicate it to the client.
For ex:
When I do
check('name').not().isEmpty().withMessage('Name must have more than 5 characters')
I get
{ value: undefined, msg: 'Name must have more than 5 characters', param 'name', location: 'body'}
// What I am looking to achieve is this
{ value: undefined, msg: 'Name must have more than 5 characters', code: 'NAME_MANDATORY' param 'name', location: 'body'}
How do I achive this with express-validator?
you can try to give the withMessage a function like this
withMessage((value, { req, location, path }) => {
return { value, location, path, otherkey:'some message' };
})
I use express-validator to check my post fields, one of my field must be a decimal or empty. I used this Schema:
request.checkBody({
'product_price': {
optional: true,
isDecimal: {
errorMessage: 'The product price must be a decimal'
}
}
})
The problem with this Schema is to not validate my post if product_price is empty, even with "optional: true".
You need to set the checkFalsy option for optional to allow defined-but-empty values:
request.checkBody({
'product_price': {
optional: {
options: { checkFalsy: true }
},
isDecimal: {
errorMessage: 'The product price must be a decimal'
}
}
});
EDIT: the documentation has been moved since posting this answer, it can now be found here.
What worked for me was using req.checkBody('optionalParam', 'optionalParam must be a number').optional().isNumber();
In case if someone is using express-validator body. You can do the following thing
router.post('apiname', [
body('product_price').trim()
.optional({ checkFalsy: true })
.isNumeric().withMessage('Only Decimals allowed'),
])