A Pen by Andrew Kirchmyer on CodePen.
Created
November 17, 2013 04:57
-
-
Save akirchmyer/7509462 to your computer and use it in GitHub Desktop.
A Pen by Andrew Kirchmyer.
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 validator = { | |
| types: {}, | |
| messages: [], | |
| config: {}, | |
| // the interface method. data should be an object | |
| validate: function(data){ | |
| var i, msg, type, checker, result_ok; | |
| // reset all messages | |
| this.messages = []; | |
| for (i in data) { | |
| if (data.hasOwnProperty(i)) { | |
| type = this.config[i]; | |
| checker = this.types[type]; | |
| if (!type) { | |
| continue; // no need to validate data | |
| } | |
| if (!checker) { | |
| throw { | |
| name: "ValidationError", | |
| message: "No handler to validate type " + type | |
| }; | |
| } | |
| result_ok = checker.validate(data[i]); | |
| if (!result_ok) { | |
| msg = "Invalid value for *" + i + "*, " + checker.instructions; | |
| this.messages.push(msg); | |
| } | |
| } //hasOwnProperty | |
| } //for | |
| return this.hasErrors(); | |
| }, //validator.validate() | |
| hasErrors: function() { //helper | |
| return this.messages.length !== 0; | |
| } | |
| }; //validator | |
| validator.types.isNonEmpty = { | |
| validate: function(value) { | |
| return value !== ""; | |
| }, | |
| instructions: "the value cannot be empty" | |
| }; | |
| validator.types.isNumber = { | |
| validate: function(value) { | |
| return !isNaN(value); | |
| }, | |
| instructions: "the value can only be a valid number" | |
| }; | |
| validator.types.isAlphaNum = { | |
| validate: function(value) { | |
| return !/[^a-z0-9]/i.test(value) | |
| }, | |
| instructions: "the value can only contain letters and numbers" | |
| }; | |
| validator.config = { | |
| first_name: 'isNonEmpty', | |
| age: 'isNumber', | |
| username: 'isAlphaNum' | |
| } | |
| var data = { | |
| first_name: "", | |
| last_name: "Kirchmyer", | |
| age: "unknown", | |
| username: "o_0" | |
| }; | |
| validator.validate(data); | |
| if (validator.hasErrors()){ | |
| console.log(validator.messages.join('\n')); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment