The Daily WTF
Validating user input is one of those problems that’s deceptively simple. The actual validation rules tend to be simple to describe: this field should be at least ten characters long, that field should match this regex, this one should be a number. But applying those rules can get cumbersome, especially when you write it yourself.
It can quickly get as thorny and difficult as date handling.
Well, Carole inherited some home-brew validation code. It’s been running in the front-end of a web app for years.
const validateGeneral = async function (importantDataStructure) { log.info(`Validating schema for ${importantDataStructure.name} `) let errors = [] try { importantDataStructure.importantField === ‘onlyThisStringIsAllowed’ ? null : errors.push(‘ Invalid importantField’) validations.NAME_VALIDATION.test(importantDataStructure.name) ? null : errors.push(‘ importantDataStructure name has invalid characters’) importantDataStructure.requiredField === undefined ? errors.push(‘ importantDataStructure is missing requiredField’) : null if (errors.length > 0) { log.error(`Errors detected for ${importantDataStructure.name} `) throw new Error(errors.toString().trim()) } } catch (err)
To read the full article click on the 'post' link at the top.