Skip to content

Instantly share code, notes, and snippets.

@tylerchilds
Created August 5, 2016 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerchilds/87b465b25fbfcf6a622eeeb26dedb698 to your computer and use it in GitHub Desktop.
Save tylerchilds/87b465b25fbfcf6a622eeeb26dedb698 to your computer and use it in GitHub Desktop.
Simple javascript validation library.
// author: { github: tylerchilds }
// date: 8/5/2016
// license: NO LICENSE
//
// Simple validation for javascript.
//
// usage:
// validate(value, rule);
//
// The rule will be used as a key to get an array of matchers
// The matchers are regular expression tests to check the value
// If the matcher fails, the error message is returned
//
// Error messages are returned if there is at least one error
// If no errors, nothing is returned
const required = (value) => {
if(! /^.+$/.test(value))
return "This field is required";
}
const validEmail = (value) => {
const regex = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
if(! regex.test(value))
return "Valid Emails Only";
}
const rules = {
email: [required, validEmail],
required: [required]
}
const validate = (value, rule) => {
const matchers = rules[rule];
let errors = [];
matchers.forEach((matcher) => {
const error = matcher(value);
if(error) errors.push(error);
}, value)
if(errors.length > 0) return errors;
}
export default validate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment