Created
March 11, 2018 05:19
-
-
Save romelperez/56390c10664da5f2d2c1ad46d3f4e91d to your computer and use it in GitHub Desktop.
Quick validation library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import isLength from 'validator/lib/isLength'; | |
import isEmail from 'validator/lib/isEmail'; | |
import isInt from 'validator/lib/isInt'; | |
import isFloat from 'validator/lib/isFloat'; | |
import matches from 'validator/lib/matches'; | |
const required = value => !!value; | |
const isLengthMin = (value, min) => isLength(value, { min }); | |
const isLengthMax = (value, max) => isLength(value, { max }); | |
const validatorsFns = { | |
required, | |
isLengthMin, | |
isLengthMax, | |
isEmail, | |
isInt, | |
isFloat, | |
matches | |
}; | |
const errorMessages = { | |
required: props => `Please fill out '${props.name}' field to submit.`, | |
isLengthMin: props => | |
`'${props.name}' field should contain at least | |
${props.options.min} characters.`, | |
isLengthMax: props => | |
`'${props.name}' field should contain no more than | |
${props.options.max} characters.`, | |
isEmail: props => `'${props.name}' field requires a valid email address.`, | |
isInt: props => `'${props.name}' field requires a valid integer number.`, | |
isFloat: props => `'${props.name}' field requires a valid floating number.`, | |
matches: props => `'${props.name}' field is invalid.` | |
}; | |
export const validateField = (fieldName, _fieldValidators, _value) => { | |
const fieldValidators = _fieldValidators || {}; | |
const value = String(_value || ''); | |
const validatorError = Object.keys(fieldValidators).find(validatorName => { | |
let validatorOpts = fieldValidators[validatorName]; | |
if (validatorOpts === false) { | |
return false; | |
} | |
validatorOpts = validatorOpts === true ? void 0 : validatorOpts; | |
const isValid = validatorsFns[validatorName](value, validatorOpts); | |
return !isValid; | |
}); | |
let errorMsg = ''; | |
if (validatorError) { | |
errorMsg = errorMessages[validatorError]({ | |
name: fieldName, | |
options: _fieldValidators[validatorError] | |
}); | |
} | |
return errorMsg || false; | |
}; | |
export const validateForm = (fields, dataMap = {}) => { | |
const errors = {}; | |
fields.forEach(field => { | |
const fieldError = validateField(field, dataMap[field.name]); | |
if (fieldError) { | |
errors[field.name] = fieldError; | |
} | |
}); | |
const areErrors = !!Object.keys(errors).length; | |
return areErrors ? errors : false; | |
}; | |
export const createValidator = fields => ({ | |
validateForm: dataMap => validateForm(fields, dataMap), | |
validateField: (fieldName, value) => | |
validateField(fieldName, fields[fieldName], value) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment