Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

349
Visualizações
Joi form validation: removing displayed errors

Here is a link to codesandbox example (Svelte). It represents a trivial register from being validated with Joi. The issue I'm facing is with clearing Joi validation error messages. I'm recording them in errors object, keys named by the input name (email, password, passwordConfirm).

Validations happens via function attached to form on:input

      const validate = async e => {
        const fields = { [e.target.name]: e.target.value };
        try {
          errors[Object.keys(fields)[0]] = null;
          await registerSchema.validateAsync(
            { ...fields },
            { abortEarly: false, allowUnknown: true }
          );
        } catch (err) {
          errors[Object.keys(fields)[0]] = err;
        }
      };

Its crude but it mostly works. It clears email and password errors alright but whatever I do passwordConfirm persists.

I don't think the issue is with my Joi schema:

export const registerSchema = Joi.object({
  email: Joi.string().email({ tlds: { allow: false } }),
  password: Joi.string().pattern(new RegExp("^[a-zA-Z0-9]{6,30}$")).trim(),
  passwordConfirm: Joi.string().valid(Joi.ref("password")).trim()
});

Am pretty sure that the bug hides somewhere in the validate function itself but - for the death of me - I can find it. I would appreciate couple of hints here.

Again, example can be seen on codesandbox.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your problem is indeed in your validate function. When you build your fields object, the only key you add to it is the currently active input: const fields = { [e.target.name]: e.target.value };, meaning that when you compare passwordConfirm to Joi.ref('password') in your schema, the latter is always an empty value because there is no password key in the object being validated!

One (crude) way around that is to make sure the password field is passed into the object being validated when the active input is passwordConfirm:

  const validate = async e => {
    const fields = { [e.target.name]: e.target.value };
    if (e.target.name === 'passwordConfirm') {
      fields.password = password;
    }
    // console.log(fields); // log object being validated
    try {
      errors[Object.keys(fields)[0]] = null;
      await registerSchema.validateAsync(
        { ...fields },
        { abortEarly: false, allowUnknown: true }
      );
    } catch (err) {
      errors[Object.keys(fields)[0]] = err;
    }
  };

Tested in your CodeSandbox and seemed to work as intended.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda