Sunday, 17 February 2019

Input validation using database?

I'm currently learning nodejs and express, and i'm writing a simple REST API.The issue is that i want to validate data.country, to see if the specified country exists in the database.But because the database query function is a promise, it never adds the error to the errors array.So how would i go about doing this?​const validator = require("validator"); const user = require("../models/Users"); const address_country = require("../models/Address_Country"); const isEmpty = require("./is-empty"); module.exports = function validateRegisterInput(data) { let errors = {}; data.firstname = !isEmpty(data.firstname) ? data.firstname : ""; //firstname if (!validator.isLength(data.firstname, { min: 2, max: 30 })) { errors.firstname = "firstname needs to be 30 char" } if (validator.isEmpty(data.firstname)) { errors.firstname = "firstname must be filled" } console.log(data.country); //tjek if country exists address_country.findOne({ where: { name: data.country } }).then(address_country => { if (!address_country) { errors.country = "country does not exists" } }) return { errors, isValid: isEmpty(errors) } } ​

Submitted February 17, 2019 at 03:14PM by CertifiedWalrus

No comments:

Post a Comment