Skip to content

Instantly share code, notes, and snippets.

@mollerjorge
Last active September 22, 2021 13:15
Show Gist options
  • Select an option

  • Save mollerjorge/c3ac42e30b66bfb3cc77756c8545a42c to your computer and use it in GitHub Desktop.

Select an option

Save mollerjorge/c3ac42e30b66bfb3cc77756c8545a42c to your computer and use it in GitHub Desktop.
var validator = {
// current configuration
// field name => validation type
config: {},
// different types of validations
types: {},
// error messages to display to the user
messages: [],
validate: function(data) {
var type, i, validationList, resultOk, msg, validationToCheck;
// reset all messages
this.messages = [];
for (key in data) {
// This is the validation in our config object, for example: 'isNonEmpty'
validationList = this.config[key] ? this.config[key] : [];
// This is the validator function for that particular validation, for example: validator.types.isNonEmpty
for (i = 0; i < validationList.length; i++) {
validationToCheck = validationList[i];
type = this.types[validationToCheck];
if (!type) {
// We don't have a validation function in place for that particular check
throw {
name: "ValidationError",
message: "No handler to validate type " + type
}
}
resultOk = type.validate(data[key]);
if (!resultOk) {
msg = "Invalid value for " + key + ", " + type.instruction;
this.messages.push(msg);
}
}
}
return this.hasErrors();
},
hasErrors: function() {
return this.messages.length > 0;
}
}
// checks the value is not empty
validator.types.isNonEmpty = {
validate: function(value) {
return value !== '';
},
instruction: 'the value cannot be empty'
}
// checks the value is a valid number
validator.types.isNumber = {
validate: function(value) {
return !isNaN(value);
},
instruction: 'the value can only be a valid number'
}
// checks if the value contains only letters and numbers
validator.types.isAlphaNum = {
validate: function(value) {
return !/[^a-z0-9]/i.test(value);
},
instruction: 'the value can only contain characters and numbers, no special characters are allowed'
}
validator.types.isString = {
validate: function(value) {
return typeof value === 'string';
},
instruction: 'the value can only be a string'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment