Skip to content

Instantly share code, notes, and snippets.

@vidaaudrey
Created June 22, 2016 17:56
Show Gist options
  • Save vidaaudrey/3911d2c148084d9424177f9cb3b18d74 to your computer and use it in GitHub Desktop.
Save vidaaudrey/3911d2c148084d9424177f9cb3b18d74 to your computer and use it in GitHub Desktop.
validation.js
const isEmpty = value => value === undefined || value === null || value === '';
const join = (rules) => (value, data) => rules.map(rule => rule(value, data)).filter(error => !!error)[0 /* first error */ ];
export function email(value) {
// Let's not start a debate on email regex. This is just for an example app!
if (!isEmpty(value) && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
return 'Invalid email address';
}
}
export function required(value) {
if (isEmpty(value)) {
return 'Required';
}
}
export function minLength(min) {
return value => {
if (!isEmpty(value) && value.length < min) {
return `Must be at least ${min} characters`;
}
};
}
export function maxLength(max) {
return value => {
if (!isEmpty(value) && value.length > max) {
return `Must be no more than ${max} characters`;
}
};
}
export function integer(value) {
if (!Number.isInteger(Number(value))) {
return 'Must be an integer';
}
}
export function oneOf(enumeration) {
return value => {
if (!~enumeration.indexOf(value)) {
return `Must be one of: ${enumeration.join(', ')}`;
}
};
}
export function match(field) {
return (value, data) => {
if (data) {
if (value !== data[field]) {
return 'Do not 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;
};
}
@drakonecrolic
Copy link

any example using the match please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment