Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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