Skip to content

Instantly share code, notes, and snippets.

@nicohvi
Created January 31, 2018 13:56
Show Gist options
  • Save nicohvi/96d741f2833ed21b2c1187d88b8f885a to your computer and use it in GitHub Desktop.
Save nicohvi/96d741f2833ed21b2c1187d88b8f885a to your computer and use it in GitHub Desktop.
import R from 'ramda';
import moment from 'moment';
const emailRegex = /\S+@\S+\.\S+/;
const validFormats = [
'D-M-YYYY',
'DD-MM-YYYY',
'D/M/YYYY',
'DD/MM/YYYY',
'D.M.YYYY',
'DD.MM.YYYY'
];
// validations
const doesNotContain = item => list => R.not(R.contains(item, list));
const equals = match => (value, props) => R.equals(value, R.prop(match, props));
const greaterThan = count => input => input.length > count;
const isDate = input => moment(input, validFormats, true).isValid();
const isEmail = input => R.not(R.isEmpty(R.match(emailRegex, input)));
const isEmpty = input => R.not(R.isEmpty(input)) && R.not(R.isNil(input));
const isExactly = count => input => input.length === count;
const isNumber = input => /^\d+$/.test(input);
// util functions
const validate = R.curry((name, predicate, message, props) => {
return predicate(R.prop(name, props), props)
? { valid: true, name }
: { valid: false, message, name };
});
const createValidationObj = (fns, props) => {
return fns.reduce((obj, fn) => {
const { valid, name, message } = fn(props);
if (valid) return obj;
obj[name] = Array.isArray(obj[name])
? obj[name].concat(message)
: [message];
return obj;
}, {});
};
export default function validator(fns = []) {
const concat = fn => validator(fns.concat(fn));
return {
// doesNotContain: (key, item, msg = '') => concat(validate(key, doesNotContain(item), msg)),
greaterThan: (count, key, msg = '') =>
concat(validate(key, greaterThan(count), msg)),
isChecked: (key, msg = '') => concat(validate(key, input => input, msg)),
isDate: (key, msg = '') => concat(validate(key, isDate, msg)),
isEmail: (key, msg = '') => concat(validate(key, isEmail, msg)),
isExactly: (count, key, msg = '') =>
concat(validate(key, isExactly(count), msg)),
isNumber: (key, msg = '') => concat(validate(key, isNumber, msg)),
matches: (key, match, msg = '') =>
concat(validate(key, equals(match), msg)),
notEmpty: (key, msg = '') => concat(validate(key, isEmpty, msg)),
funcs: () => fns,
isValid: props => createValidationObj(fns, props)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment