Skip to content

Instantly share code, notes, and snippets.

@blackakula
Last active April 19, 2018 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackakula/a99bc058c2064711904733bd044819bc to your computer and use it in GitHub Desktop.
Save blackakula/a99bc058c2064711904733bd044819bc to your computer and use it in GitHub Desktop.
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}]
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