Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple object validation code. Loosely based on https://medium.com/javascript-inside/form-validation-as-a-higher-order-component-pt-1-83ac8fd6c1f0#.6yiftk939, writen in a more easy to understand manner
const getErrors = (inputData, validationRules, globalOptions) => {
const errors = {}
const addError = (key, errorMessage) => {
if(!(key in errors)) errors[key] = []
errors[key].push(errorMessage)
}
Object.keys(inputData).forEach((key) => {
// skip if there is no rule for the key
if(!(key in validationRules)) return;
const value = inputData[key]
validationRules[key].forEach((rule) => {
const [ validator, message, validatorOptions ] = Array.isArray(rule)
? rule // Array syntax
: [rule.validator, rule.message, rule.options] // Object syntax
// same props are used for the validator and message functions
const props = [
value,
key,
inputData,
validationRules,
validatorOptions,
globalOptions
]
const valid = validator(...props)
if(!valid){
const errorMessage = (typeof message === 'function')
? message(...props) // String maker
: message // String
addError(key, errorMessage)
}
})
})
return errors
}
// USAGE
const isGreaterThan = (size) => (value) => value > size
const isGreaterOrEqualsThan = (size) => (value) => value >= size
const hasLengthGreaterThan = (size) => (value) => isGreaterThan(size)(value.length)
const passwordMatches = (passwordInputKey) => (value, _, inputData) => value === inputData[passwordInputKey]
const hasCapitalLetter = (value) => /[A-Z]/.test(value)
const validationRules = {
name: [
[hasLengthGreaterThan(6), "Minimum length of 6 is required."],
[hasCapitalLetter, "Should contain at least one uppercase letter."],
],
age: [
[isGreaterOrEqualsThan(18), "Minimum age required is 18."]
],
password: [
[hasLengthGreaterThan(6), "Minimum length of 6 is required."],
],
passwordRepeat: [
// Alternative rule syntax as an object
{
validator: passwordMatches('password'),
// Message can also be a function
message: (value, key, inputData, validationRules, validatorOptions) =>
`Must be equals to field ${validatorOptions.fieldName}`,
// You can pass options which will be passed as the
// 5th argument for validator and message function
options: {fieldName: "Password"}
}
]
}
const inputData = {
name: "phil",
age: 17,
password: '12345678',
passwordRepeat: '1234567'
}
// You can pass an global options object as the 3rd
// argument which will be passed as the 6th argument
// for validator and message function
const errors = getErrors(inputData, validationRules)
console.log(errors)
// {
// name: [ 'Minimum length of 6 is required.', 'Should contain at least one uppercase letter.' ],
// age: [ 'Minimum age required is 18.' ],
// passwordRepeat: [ 'Must be equals to field Password' ]
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.