1
I created an express server and a class to structure my validation errors. This is how it is:
function Error() {
this.anyError = false
this.errors = {}
}
Error.prototype.addError = function (attr, error) {
this.anyError = true
this.errors[attr] = error
}
module.exports = new Error()
Then in the validation classes I use this module like this:
const validator = require("validator")
const Error = require("./error")
function validateCustomer(body) {
let helper = Error
if ( ! validator.isEmail(body.email)) {
helper.addError("email", "Invalid email.")
}
if ( ! validator.isLength(body.document, {min: 14, max: 14})) {
helper.addError("document", "Invalid document.")
}
if ( ! validator.isLength(body.social_name, {min: 5})) {
helper.addError("social_name", "Invalid social name, minimal length is 5.")
}
if ( ! validator.isMobilePhone(body.contact_phone, 'pt-BR')) {
helper.addError("contact_phone", "Invalid mobile phone.")
}
return {
invalid: helper.anyError,
errors: helper.errors
}
}
module.exports = {
customerValidator: validateCustomer
}
The route is as follows:
router.post('/', [verifyAdmin, function(req, res) {
if(req.body) {
let validation = customerValidator(req.body.customer)
if (validation.invalid) {
return res.status(200).json({errors: validation.errors, status: 'invalid'})
}
// encripta a senha
const newCustomer = new Customers(req.body.customer)
newCustomer.encripted_password = customerCript(newCustomer.encripted_password)
newCustomer
.save()
.then(function(customer) {
delete customer.encripted_password
res.status(201).json({message: 'record created successfully', customer})
})
.catch(function(error){
res.status(500).json({error})
})
} else {
return status(500).json({error: 'body not found'})
}
}])
Every time I submit something that is not valid it falls right in the validation, but once I tidy up the data is as if the validation is persistent on the server.
Surely I’ve done something wrong with regard to require
, scope and etc. Could you please help me?
If I were you, I’d use a different name than
Error
for its function, since so you are overwriting theError
native Javascript. Maybe you already know this. Just a note. :)– Luiz Felipe
@Luizfelipe knew no! Thank you
– vinicius gati
:) I forgot to mention in the other comment... Could you include in your question the code of your route in express? Probably the
app.post
...– Luiz Felipe
@Luizfelipe Feito!
– vinicius gati