sc-react-ions
Version:
An open source set of React components that implement Ambassador's Design and UX patterns.
60 lines (48 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validate = undefined;
var _immutable = require('immutable');
// The validate utility checks the provided values against the provided validation.
// The utility receives two arguments in the following format:
//
// formValidation = Immutable.fromJS({
// email: {
// validators: [
// {
// validator: isRequired,
// message: 'This field is required'
// },
// {
// validator: isValidEmail,
// message: 'Please provide a valid email'
// }
// ]
// }
// })
//
// fields = Map({
// email: 'test@example.com'
// })
var validate = exports.validate = function validate() {
var formValidation = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _immutable.Map)();
var fields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _immutable.Map)();
// Loop through validated fields
return formValidation.reduce(function (errors, fieldValidation, key) {
// Get the currently set value
var fieldValue = fields.get(key);
// Helper that runs validation function and returns error message
var getFieldError = function getFieldError(v, f) {
var validator = f.get('validator');
var message = f.get('message');
return !validator(fieldValue) ? message : v;
};
// Get the first error where not valid (false if valid)
var fieldError = fieldValidation.get('validators').reduceRight(getFieldError, '');
// If there is an error append to errors
if (fieldError) return errors.set(key, fieldError);
// If no error, don't add the field to errors
return errors;
}, (0, _immutable.Map)());
};