Post data is validated from joi library like how to use validation, valid email, length etc. And how to send validation error to the server.
1.Create new request for post
2. Send body raw data
{
"first_name": "",
"last_name": "",
"mobile_no": "",
"email_id": "",
"password" : ""
}
Create new post route for the request handle
router.post('/', (req, res, next) => {
});
1. Install joi module in express
2. Import joi in route page
import Joi from 'joi';
set validation rules for validate body data
const simple_validate = Joi.object({
first_name : Joi.string().required(), // require first name
last_name : Joi.string().required(), // require last name
mobile_no : Joi.string().required().length(10), // require mobile no and exact length is 10
email_id : Joi.string().email().required(), // valid email and require email
password : Joi.string().required().min(6), // require password and minimum length 6
});
Call validate function for apply all rules
const { error } = simple_validate.validate(req.body);
if any field mismatch this rule then throw error from joi validate class.
if(error){
return res.json({error : error.message});
}
If error object is get then return error message to client side.
Ex. Show error one by one
{
"error": "\"first_name\" is not allowed to be empty"
}
{
"error": "\"last_name\" is not allowed to be empty"
}
{
"error": "\"mobile_no\" is not allowed to be empty"
}
{
"error": "\"mobile_no\" length must be 10 characters long"
}
{
"error": "\"email_id\" is not allowed to be empty"
}
{
"error": "\"email_id\" must be a valid email"
}
{
"error": "\"password\" is not allowed to be empty"
}
{
"error": "\"password\" length must be at least 6 characters long"
}
{
"first_name": "deepak",
"last_name": "tailor",
"mobile_no": "1234567890",
"email_id": "deepak@email.com",
"password_data": {
"password": "123456",
"confirm_password": "123456"
}
}
email_id : Joi.string().email().required(), // valid email and require email
password_data : Joi.object({
password : Joi.string().required().min(6), // require password and minimum length 6
confirm_password : Joi.string().required().min(6), // require confirm password and minimum length 6
}),
{
"error": "\"password_data.password\" is not allowed to be empty"
}
{
"error": "\"password_data.confirm_password\" length must be at least 6 characters long"
}
My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in