Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.