I've created a route as a validation all my routes, I want this to handle all my requests and validate them, problem is i want to check if attributes are in the request, not the data just the attributes, lets say the user has an email but the others don't, I want to check if the body has email attribute to run a certain code to validate this email.
how do I know if the
req.body.email;
is in the body?
var express = require('express');
var router = express.Router();
router.use('/', function(req, res, next) {
var record = req.body.record,
email = record.email,
phone_number = record.phone_number,
school_id = req.body.schoolId;
console.log("validator");
if (record) {
if (what is the condition here to check
if the body has email)
req.asyncValidationErrors()
.then(function() {
next();
}).catch(function(errors) {
if (errors) {
res.json({
status: "error",
message: "please make sure your data is correct and your email and phone number are not valid"
});
return;
}
});
});
module.exports = router;
To know whether the email
is in body, You need to check for undefined
. An attribute which isn't in the body will give you undefined
when accessed.
if (body.email === undefined) {
console.log('email attribute is not in the body, hence it comes here');
return res.json({
status: "error",
message: "please make sure your data is correct and your email is valid"
});
}
If you've lodash in your app.
let _ = require('lodash');
let body = req.body;
if(_.isUndefined(body.email)) {
console.log('email attribute is not in the body, hence it comes here');
return res.json({
status: "error",
message: "please make sure your data is correct and your email is valid"
});
}
Try using the npm express-validator to do all your validation on middleware.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.