-
-
Save robotlolita/28abec89a3de6f45c3e99b84f9942d40 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const Validation = require('folktale/validation'); | |
const { Success, Failure } = Validation; | |
// valida se uma string não é vazia | |
const hasText = (value, name) => | |
if (value != "") Success(value) | |
else Failure([{ code: 'required', name }]); | |
// valida se uma selecao não é vazia | |
const hasSelection = (value, name) => | |
if (value != "") Success(value) | |
else Failure([{ code: 'selection-required', name }]); | |
// tipos de validação suportados no atributo data-validation | |
const fieldValidations = { | |
selection: (input, name) => hasSelection(input.value, name), | |
'not-empty': (input, name) => hasText(input.value, name) | |
}; | |
Reflect.setPrototypeOf(fieldValidations, null); // remove métodos de Object.prototype | |
// adiciona o campo original no erro para permitir mostrar o erro em contexto | |
const withField = (field) => (errors) => { | |
errors.map(e => ({ ...e, field })); | |
} | |
// valida um único campo do formulario | |
const validateField = (field) => { | |
const id = field.getAttribute('data-validation'); | |
if (id) { | |
const validation = fieldValidations[id]; | |
if (!validation) { | |
console.warn(`Validation ${id} is not defined.`); | |
return Failure([{ code: 'unknown-validation', id }]); | |
} else { | |
return validation(field, field.getAttribute('data-name') || field.name).mapFailure(withField(field)); | |
} | |
} else { | |
return Success(); | |
} | |
} | |
// valida um formulario | |
const validateForm = (form) => { | |
const fields = Array.from(form.querySelectorAll('[data-validation]')); | |
return Validation.collect(fields.map(validateField)); | |
} | |
// converte o objeto de erro para uma mensagem de erro em portugues | |
const toNaturalLanguage = (error) => { | |
switch (error.code) { | |
case 'required': return `${error.name} deve ser preenchido.`; | |
case 'selection-required': return `selecione ao menos uma opço de ${error.name}`; | |
case 'unknown-validation': return `validação ${error.id} não foi definida`; | |
default: throw new Error(`Unknown error code ${error.code}`); | |
} | |
} | |
// main | |
function validaCamposForm() { | |
const validation = validateForm(document.querySelector('#some-form')); | |
validation.matchWith({ | |
Success: () => { | |
/* segue a vida aqui */ | |
}, | |
Failure: ({ value: errors }) => { | |
// Tu podes mostrar todos os erros pro usuario | |
alert(errors.map(toNaturalLanguage).join('\n')); | |
// Tu pode adicionar classes nos campos errados | |
errors.filter(e => e.field).map(e => e.field.classList.add('errored')); | |
// Tu pode mudar o foco para o primeiro campo errado | |
const first = errors.filter(e => e.field)[0]; | |
if (first) first.focus(); | |
// Etc. | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment