Created
January 28, 2019 18:04
-
-
Save sanfilippopablo/c88889039990375afc881132536a8b26 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const isEmpty = value => value === undefined || value === null || value === ""; | |
const join = rules => (value, data) => | |
rules.map(rule => rule(value, data)).filter(error => !!error)[0]; | |
export function email(value) { | |
if ( | |
!isEmpty(value) && | |
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) | |
) { | |
return "Invalid e-mail address"; | |
} | |
} | |
export function slug(value) { | |
if (!isEmpty(value) && !/^[A-Z0-9._-]+$/i.test(value)) { | |
return "Enter a valid name consisting of letters, numbers, underscores or hyphens"; | |
} | |
} | |
export function setRequired(value) { | |
if (value.size === 0) { | |
return "This field is required"; | |
} | |
} | |
export function required(value) { | |
if (isEmpty(value)) { | |
return "This field is required"; | |
} | |
} | |
export function minLength(min) { | |
return value => { | |
if (!isEmpty(value) && value.length < min) { | |
return `It must be at least ${min} characters`; | |
} | |
}; | |
} | |
export function maxLength(max) { | |
return value => { | |
if (!isEmpty(value) && value.length > max) { | |
return `It must be at most ${max} characters`; | |
} | |
}; | |
} | |
export function integer(value) { | |
if (!Number.isInteger(Number(value))) { | |
return "It must be an integer number"; | |
} | |
} | |
export function isNumber(value) { | |
if (isNaN(value)) { | |
return "It must be a valid number"; | |
} | |
} | |
export function oneOf(enumeration) { | |
return value => { | |
if (!~enumeration.indexOf(value)) { | |
return `It must be one of: ${enumeration.join(", ")}`; | |
} | |
}; | |
} | |
export function match(field) { | |
return (value, data) => { | |
if (data) { | |
if (value !== data[field]) { | |
return "It must match"; | |
} | |
} | |
}; | |
} | |
export function createValidator(rules) { | |
return (data = {}) => { | |
const errors = {}; | |
Object.keys(rules).forEach(key => { | |
const rule = join([].concat(rules[key])); // concat enables both functions and arrays of functions | |
const error = rule(data[key], data); | |
if (error) { | |
errors[key] = error; | |
} | |
}); | |
return errors; | |
}; | |
} | |
export function isValid(errors) { | |
return Object.keys(errors).find(key => errors[key] !== null) === undefined; | |
} | |
// USAGE | |
const v = createValidator({ | |
email: [required, email], | |
password: [required, minLength(8)] | |
}) | |
const errors = v.validate({email: "not gonna pass": "thiswillsurellypass"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment