I am attempting to use Express Validator to validate an async POST query on the server side. PERN stack. Express Validator does not appear to validate anything since it always returns the same response regardless of input. Here is my code. I have no idea why this doesn't work. Please help.
const { validationResult, check } = require('express-validator');
const myValidationResult = validationResult.withDefaults({
formatter: error => {
return {
myLocation: error.location,
};
},
});
app.post("/pathToContactTable",
[
check('req.body.aName')
.not().isEmpty() // checks appear to do nothing. violating them does nothing.
],
async (req, res, next) => {
console.log(req.body.aName); // prints out exactly what it should
var err = myValidationResult(req);
console.log(!err.isEmpty());
if (!err.isEmpty()) {
console.log(err.mapped())
return res.status(400).json({errors: err.array() });
} else {
try {
const { aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle } = req.body;
const newApplicant = await pool.query(`INSERT INTO applicantContactTable
( applicantName, applicantLastName, applicantPhone, applicantEmail, jobTitle1, jobDesc1, jobTitle2, jobDesc2, jobTitle3, jobDesc3, educationTitle, educationYear, certificationTitle)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING *`,
[aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle]
);
res.json(newApplicant.rows[0]);
} catch (err) {
console.error(err.message);
}
}
});
I am expecting to have differences in validation result depending on entering or not entering a value to req.body.aName via the form on the front end -->
const [aName, setAName] = useState("John");
const onSubmitForm = async (e) => {
e.preventDefault();
//ERROR CHECKS with error messages on screen prior to POST sending
//name first
var firstName = document.getElementById('firstNameInput').value;
if (validateName(firstName)) {
document.getElementById('firstName_error').classList.add('hidden');
} else if (!validateName(firstName)){
document.getElementById('firstName_error').classList.remove('hidden');
}
try { const body = { aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle }; const response = await fetch("http://localhost:5000/pathToContactTable", method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
getApplicants();
// window.location = "/"; <-- This WAS inelegant and was replaced with a call to getApplicants();
} catch (err) {
console.log('this line fires in catch block of client POST')
console.error(err.message);
}
};
CodePudding user response:
You should only pass the field name to check()
:
check('aName')
It will validate that field against different request objects (as explained in the manual).
If you want to limit the check only to req.body.aName
, use:
body('aName')