Last active
April 19, 2018 14:29
-
-
Save blackakula/a99bc058c2064711904733bd044819bc to your computer and use it in GitHub Desktop.
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
import {Validator} from 'Validator' | |
// Usage | |
console.log(Validator('valid@email.com', {type: "email", placeholder: "your email"})) | |
// [] | |
console.log(Validator('invalid.email.com, but no type="email"', {placeholder: "your email"})) | |
// [] | |
console.log(Validator('invalid.email.com', {type: "email", placeholder: "your email"})) | |
// [{error: "Not valid email address"}] | |
console.log(Validator('Check max length', {maxLength: "6"})) | |
// [{error: "More than %s symbols", length: 6}] |
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
export const Validator = (value, props, ...customValidators) => (validators => validators.reduce((errors, validate) => [...errors, ...validate(value, props)], []))([ | |
// Here the list of validators | |
(value, props) => typeof value !== 'string' | |
|| props.type !== 'email' | |
|| /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value.toLowerCase()) ? [] : [{error: Errors.EMAIL}], | |
(value, props) => typeof value !== 'string' | |
|| typeof props.maxLength === 'undefined' | |
|| parseInt(props.maxLength) >= value.length ? [] : [{error: Errors.MAXLENGTH, length: parseInt(props.maxLength)}], | |
/** | |
* Other validators here | |
* We can extend wherever we want following the interface | |
* const newAwesomeValidator = (value, props, ...customValidators) => Validator( | |
* value, | |
* props, | |
* (value, props) => [], | |
* (value, props) => [], | |
* (value, props) => [], | |
* ...customValidators | |
* ) | |
*/ | |
...customValidators | |
]) | |
export const Errors = { | |
EMAIL: "Not valid email address", | |
MAXLENGTH: "More than %s symbols" | |
} | |
export default {Validator, Errors} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment