envoc-form
Version:
Envoc form components
78 lines (77 loc) • 3.02 kB
JavaScript
export var required = function (value) {
return Array.isArray(value)
? value.length > 0
? undefined
: 'Required'
: value || value === false || value === 0
? undefined
: 'Required';
};
/** Asserts that the value is a certain number of characters. numbers are coerced to a string */
export var length = function (len) { return function (value) {
var hasError = getLengthOfValue(value) !== len;
return !hasError ? undefined : "Length must be ".concat(len);
}; };
export var integer = function (val) {
if (!val) {
return undefined;
}
if (!Number.isInteger(typeof val === 'number' ? val : parseFloat(val))) {
return 'Must be a whole number';
}
};
export var maxLength = function (len) { return function (value) {
var hasError = getLengthOfValue(value) > len;
return !hasError ? undefined : "Maximum length ".concat(len, " exceeded");
}; };
export var maxCount = function (count) { return function (value) {
var hasError = !!value && value.filter(function (x) { return !x.isDeleted; }).length > count;
return !hasError ? undefined : "Should not have more than ".concat(count);
}; };
export var minCount = function (count) { return function (value) {
var hasError = !value || value.filter(function (x) { return !x.isDeleted; }).length < count;
return !hasError ? undefined : "Should have at least ".concat(count);
}; };
export var maxValue = function (max) { return function (value) {
var hasError = !!value && value > max;
return !hasError ? undefined : "Maximum value ".concat(max, " exceeded");
}; };
export var minValue = function (min) { return function (value) {
var hasError = !value || value < min;
return !hasError ? undefined : "Minimum value ".concat(min, " not met");
}; };
/** Validate for a ZIP Code. Accepts formats: ##### and #####-#### */
export var zipCode = function (value) {
return value && !/^[0-9]{5}(?:-[0-9]{4})?$/.test(value)
? 'Invalid ZIP Code'
: undefined;
};
/** One of the validators provided must be true. */
export var any = function (validatorList) {
return function (value) {
if (validatorList.length === 0 || !value) {
return;
}
return validatorList.reduce(function (isAnyTrue, x) { return (isAnyTrue ? isAnyTrue : x(value)); }, undefined);
};
};
function getLengthOfValue(value) {
if (value === null) {
return 0;
}
switch (typeof value) {
case 'undefined':
return 0;
case 'string':
return value.length;
case 'number':
// TODO: this seems iffy to me - what if the actual visible value is a fixed length or some special format (e.g. with commas?)
return value.toString().length;
default:
assertUnreachable(value);
return 0;
}
}
function assertUnreachable(x) {
return null;
}