i want that if the number of digits in the input field in less/more than 14(for example) then joi should return an error.
how can i do this with the type of number not for string.
i want that if the number of digits in the input field in less/more than 14(for example) then joi should return an error.
how can i do this with the type of number not for string.
Validation for 10 digit numeric mobile number are given below
joi.string().length(10).pattern(/^[0-9]+$/).required(),
You should change the rule as per your requirement. pattern(your regex) is used to accept only digits, length() is used to validate how many character validation accepts and only work with string function.
\d
in js regex. Hence you can also write joi.string().length(10).pattern(/^\d+$/).required(),
–
Gurrola You can use custom validator
Joi.object({
phone: Joi
.string()
.custom((value, helper) => {
// you can use any libs for check phone
if (!checkPhone(value)) {
return helper.message("phone is incorrect");
} // this is what was added
return value
})
}).validate({
phone: '+79002940163'
});
Docs: https://github.com/hapijs/joi/blob/master/API.md#anycustommethod-description
Validation for 10 digit numeric mobile number with custom error message are given below
joi.string().regex(/^[0-9]{10}$/).messages({'string.pattern.base': `Phone number must have 10 digits.`}).required()
Unfortunately, Hapi/joi doesn't presently have a digit count check for numbers. While Sachin Shah is correct that you must convert the number to a string, you must also pass a regex to the validator to ensure that only numeric values are allowed:
joi.string().length(14).regex(/^\d+$/)
For Mobile number:
mobile: Joi.number().integer().min(10 ** 9).max(10 ** 10 - 1).required().messages({
'number.min': 'Mobile number should be 10 digit.',
'number.max': 'Mobile number should be 10 digit'
})
For other digit check:
yourparam: Joi.number().integer().min(1000).max(9999).required().messages({
'number.min': 'OTP should be 4 digit.',
'number.max': 'OTP should be 4 digit'
})
For example birth_year an integer between 1900 and 2013
birth_year: Joi.number()
.integer()
.min(1900)
.max(2013)
You can use like this for number with joi. For reference Official Readme
Like this u can pass your min and max values to validate
Joi converts strings if it can by default, that's all in the documentation. Globally disable convert or use strict on that specific schema.
minCount: Joi.number().strict()
if you are using @hapi/joi
You can use it's min
and max
methods.
joi.number().min(14)
joi.number().max(14)
If it's fine with string then you can do this also.
joi.string().length(14).required()
And while you read the data for db operation, you can use +
with value. It will convert your string into integer. But make sure your db allows this big value as a integer if database is mysql. I suggest you to user string as a data type.
let obj = {
number: +req.body.number
}
© 2022 - 2024 — McMap. All rights reserved.