Skip to content

Instantly share code, notes, and snippets.

@sergeyt
Created April 16, 2017 10:09
Show Gist options
  • Save sergeyt/7c8e3b73c58d8346f2e1a3c6d85d8242 to your computer and use it in GitHub Desktop.
Save sergeyt/7c8e3b73c58d8346f2e1a3c6d85d8242 to your computer and use it in GitHub Desktop.
Form Validation
import Immutable from 'immutable';
import {reduce} from 'lodash';
type ErrorMap = Immutable.Map;
type Validator = (value, path, form) => ErrorMap;
function validationRules(rules) {
return (value, path, form) => {
return reduce(rules, (result, fn, key) => {
if (path.contains(key)) {
return result.merge(fn(value, path, ctx));
}
return result;
}, Immutable.Map());
});
}
// TODO consider to support rules objects too
function combine(...validators) {
return (value, path, form) => {
return reduce(validators, (result, fn) => {
return result.merge(fn(value, path, form));
}, Immutable.Map());
};
}
function makePredicate(predicate, error) {
return (value, path, form) => {
if (!predicate(value)) {
return Immutable.Map({[path]: error});
}
return Immutable.Map();
};
}
function isNotEmpty(error = 'is empty') {
return makePredicate(val => !val, error);
}
function isUniqueParameter(error = 'not unique') {
return (value, path, form) => {
if (path.contains('parameters.')) {
const i = path.lastIndexOf('.');
const paramsKey = path.substr(0, i);
const name = path.substr(i + 1);
const params = form.getIn(paramsKey);
if (params.find(t => t.get('name') === name)) {
return Immutable.Map({[path]: error});
}
}
return Immutable.Map();
};
}
// example
const validateForm = validationRules({
name: combine(isNotEmpty(), isUniqueParameter())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment