Created
August 5, 2016 23:03
-
-
Save tylerchilds/87b465b25fbfcf6a622eeeb26dedb698 to your computer and use it in GitHub Desktop.
Simple javascript validation library.
This file contains 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
// 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