Skip to content

Instantly share code, notes, and snippets.

@dexygen
Last active December 31, 2015 03:39
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 dexygen/7928746 to your computer and use it in GitHub Desktop.
Save dexygen/7928746 to your computer and use it in GitHub Desktop.
Form validation module with Promise-like interface (work in progress)
var values = {
chessIsGame : false,
chessChampionSurname : 'Carlsen'
};
var rules = {
chessIsGame : function(value) {
if (value !== true) {
return new Error("Chess IS a Game");
}
},
chessChampionSurname : function(value) {
var testValue = $.trim(value).toUpperCase();
var chessChampSurname = 'CARLSEN';
if (testValue !== chessChampSurname) {
return new Error(chessChampSurname + " is the surname of the World Chess Champion");
}
}
}
processSubmission({
values : values,
rules : rules
}).validate().then({
stateValid : function(values) {
console.log('stateValid')
},
stateInvalid : function(errors) {
console.log('stateInvalid')
}
});
function processSubmission(options) {
return {
validate : function() {
var examResults = examineValues();
var state = examResults.valid ? {
key : 'stateValid',
content : examResults.values
} : {
key : 'stateInvalid',
content : examResults.errors
};
return {
then : function(stateHandlers) {
stateHandlers[state.key](state.content);
}
}
}
}
function examineValues() {
var allValues = options.values;
var examResults = _.reduce(_.keys(allValues), function(examResults, key) {
var value = allValues[key];
var result = options.rules[key](value, allValues) || value;
if (result instanceof Error) {
examResults.errors[key] = result.message;
}
else {
examResults.values[key] = value;
}
return examResults;
}, {errors: {}, values: {}});
return _.extend({}, examResults, {
valid : _.isEmpty(examResults.errors)
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment