Skip to content

Instantly share code, notes, and snippets.

@Piterden
Created August 24, 2017 21:45
Show Gist options
  • Save Piterden/e4bf8802115866998b1620c0c6e3c99c to your computer and use it in GitHub Desktop.
Save Piterden/e4bf8802115866998b1620c0c6e3c99c to your computer and use it in GitHub Desktop.
Validator.js
import extend from 'extend'
/**
* Class Validator.
*
* @class Validator
*/
export default class Validator {
/**
* Constructs the object.
*
* @param {Object} config The configuration
*/
constructor (config) {
if (config === undefined) {
config = this.defaults
}
this.config = extend(this.defaults, config)
}
/**
* Get the default config
*
* @return {Object}
*/
get defaults () {
return {
styles: {
success: {
borderColor: '#4CAF50',
boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(76, 175, 80, 0.6)',
},
error: {
borderColor: '#E91E63',
boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(233, 30, 99, 0.6)',
},
},
rules: {
name (value) {
return value.length > 1
},
phone (value) {
return value.match(/\+7 \(\d\d\d\) \d\d\d-\d\d-\d\d/)
}
}
}
}
/**
* Pass the validation
*
* @param {HTMLElement} el
*/
pass (el) {
this.setStyle(el, this.config.styles.success)
}
/**
* Fail the validation
*
* @param {HTMLElement} el
*/
fail (el) {
this.setStyle(el, this.config.styles.error)
}
/**
* Check the value
*
* @param {Event} e
*/
check (e) {
return this.config.rules[e.target.name](e.target.value)
? this.pass(e.target)
: this.fail(e.target)
}
/**
* Sets the style.
*
* @param {HTMLElement} el
* @param {Object} styles The styles
*/
setStyle (el, styles) {
Object.keys(styles).forEach(prop => {
el.style[prop] = styles[prop]
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment