Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Created August 23, 2020 05:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sayhicoelho/019a5ab14e901ecf02ca3ab6448aa857 to your computer and use it in GitHub Desktop.
class Validator {
constructor(data, rules) {
this.data = data
this.rules = rules
this.errors = {}
}
get validations() {
return {
required(field) {
if (!this.data[field]) {
return `The ${field} is required.`
}
},
string(field) {
if (typeof this.data[field] !== 'string') {
return `The ${field} must be a string.`
}
},
integer(field) {
if (!Number.isInteger(this.data[field])) {
return `The ${field} must be an integer.`
}
},
maxlength(field, max) {
if (this.data[field].length > max) {
return `The ${field} may not be greater than ${max} characters.`
}
},
minvalue(field, min) {
if (this.data[field] < min) {
return `The ${field} must be at least ${min}.`
}
}
}
}
async validate() {
for (const field in this.rules) {
const validations = this.rules[field].split('|')
for (const validation of validations) {
const splitted = validation.split(':')
const validationName = splitted[0]
const params = (splitted[1] && splitted[1].split(',')) || []
const message = await this.validations[validationName].call(this, field, ...params)
if (message) {
this.errors[field] = message
break
}
}
}
if (Object.keys(this.errors).length > 0) {
throw this.errors
}
}
}
// Example
const data = {
name: 'Renan',
age: 24
}
const rules = {
name: 'required|string|maxlength:10',
age: 'required|integer|minvalue:18'
}
const validator = new Validator(data, rules)
validator.validate()
.then(() => {
console.log('Passed')
})
.catch(err => {
console.error(err)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment