Skip to content

Instantly share code, notes, and snippets.

@kcabading
Created February 21, 2017 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcabading/c944d799bf97e0e06df411a2da8f0bfb to your computer and use it in GitHub Desktop.
Save kcabading/c944d799bf97e0e06df411a2da8f0bfb to your computer and use it in GitHub Desktop.
JS helper to Parse validation errors and messages returned by https://github.com/hapijs/joi
'use strict';
const _ = require('lodash');
const parseReason = function (message) {
const regexBecause = /because \[(.*?)(\]|$)/;
let parsedMessage = message;
if (regexBecause.test(message)) {
parsedMessage = regexBecause.exec(message)[1];
}
if (regexBecause.test(parsedMessage)) {
parsedMessage = parseReason(parsedMessage);
}
return parsedMessage;
};
const parseValidation = function (response) {
const validation = response && response.validation;
const message = response && response.message;
const error = response && response.error;
const result = {
error: undefined,
hasError: {},
help: {}
};
if (validation && validation.keys) {
const arMessage = message.split(".");
const arField = _.uniqBy(validation.keys, function (e) {
return e;
});
// initialise length
let intLength = arMessage.length;
for (let i = 0 ; i <= intLength; i++ ) {
const forField = arField[i];
const reason = parseReason(arMessage[i]);
result.hasError[forField] = true;
result.help[forField] = reason;
}
}
else if (message) {
result.error = message;
}
else if (error) {
result.error = error;
}
return result;
};
module.exports = parseValidation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment