Last active
December 17, 2015 12:19
-
-
Save asci/5609188 to your computer and use it in GitHub Desktop.
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 = (function (){ | |
var rules = []; | |
return { | |
_add: function (rule) { | |
if (rules[rule.objectName] === undefined) { | |
rules[rule.objectName] = []; | |
} | |
rules[rule.objectName].push(rule); | |
}, | |
configurate: function (rules) { | |
for (var i = 0, len = rules.length; i < len; i++) { | |
this._add(rules[i]); | |
} | |
}, | |
check: function (field, value) { | |
if (rules[field] === undefined) return; | |
if (rules[field].length === 0) return; | |
var valid = true, messages = []; | |
for (var i = 0; i < rules[field].length; i++) { | |
if (rules[field][i].type === 'lengthLessThan') { | |
if (value.length > rules[field][i].value) { | |
valid = false; | |
messages.push('Error, ' + value.length + ' great than ' + rules[field][i].value); | |
continue; | |
} | |
} | |
if (rules[field][i].type === 'greatThan') { | |
if (value <= rules[field][i].value) { | |
valid = false; | |
messages.push('Error, ' + value + ' less or equal ' + rules[field][i].value); | |
continue; | |
} | |
} | |
if (rules[field][i].type === 'notEmpty') { | |
if ((String(value).length < 1)||(!/\S/.test(value))) { | |
valid = false; | |
messages.push('Error, ' + value + ' is empty!'); | |
continue; | |
} | |
} | |
if (rules[field][i].type === 'validDate') { | |
if (String(value) === 'Invalid Date') { | |
valid = false; | |
messages.push('Error, ' + value + ' is not a date!'); | |
continue; | |
} | |
} | |
if (rules[field][i].type === 'isNumber') { | |
if (isNaN(+value)) { | |
valid = false; | |
messages.push('Error, ' + value + ' is not valid number!'); | |
continue; | |
} | |
} | |
if (rules[field][i].type === "valueFromSet") { | |
if (rules[field][i].value.indexOf(value) === -1) { | |
valid = false; | |
messages.push('Error, ' + value + ' is not from set'); | |
continue; | |
} | |
} | |
}; | |
return {valid:valid, messages:messages, field:field}; | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment