Last active
December 31, 2015 03:39
-
-
Save dexygen/7928746 to your computer and use it in GitHub Desktop.
Form validation module with Promise-like interface (work in progress)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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