Last active
October 11, 2018 15:52
-
-
Save alanleite/57626a51d080ad00733641ec41edabaa to your computer and use it in GitHub Desktop.
Validator like joi
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 validateEmail from 'validator/lib/isEmail' | |
const exec = (func) => { | |
return (val) => { | |
try { | |
return func(val) | |
} catch (error) { | |
return false | |
} | |
} | |
} | |
const builder = { | |
'string': () => { | |
const ctx = { | |
validators: [] | |
} | |
ctx.required = () => { | |
ctx.validators.push({ | |
message: 'Este campo não é obrigatório', | |
action: (val) => !!val | |
}) | |
return ctx | |
} | |
ctx.email = () => { | |
ctx.validators.push({ | |
message: 'Este campo não é um e-mail válido', | |
action: exec(validateEmail) | |
}) | |
return ctx | |
} | |
ctx.min = (min) => { | |
ctx.validators.push({ | |
message: `Quantidade mínima de caracteres é ${min}`, | |
action: exec(value => (value.length >= min)) | |
}) | |
return ctx | |
} | |
ctx.max = (max) => { | |
ctx.validators.push({ | |
message: `Quantidade máxima de caracteres é ${max}`, | |
action: exec(value => (value.length <= max)) | |
}) | |
return ctx | |
} | |
ctx.validators.push({ | |
message: 'Este campo não é do tipo texto', | |
action: (value) => (typeof value === 'string') | |
}) | |
return ctx | |
} | |
} | |
const validate = (schema, data) => { | |
const errors = [] | |
for (const key in schema) { | |
schema[key].validators.forEach(val => { | |
const isValid = val.action(data[key]) | |
if (!isValid) { | |
errors.push({ | |
key: key, | |
message: val.message | |
}) | |
} | |
}) | |
} | |
return errors | |
} | |
export { validate, builder } |
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 { validate, builder } from './form-validator' | |
test('Testando form validator', () => { | |
const schema = { | |
nome: builder | |
.string() | |
.required() | |
.email() | |
.min(3) | |
} | |
const result = validate(schema, { | |
nome: 'asd@asd.com' | |
}) | |
console.log(result) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment