How to decrease the amount of if/Else for the same validation of different object properties?

Asked

Viewed 65 times

2

I have some validations of mandatory fields in my application and today I do this way:

verificarObrigatorios(): boolean{
    if(!this.pessoa.nome)
    {
        this.toastr.showMessage("Nome Obrigatório")
        return false;
    }
    if(!this.pessoa.cpf)
    {
        this.toastr.showMessage("CPF Obrigatório")
        return false;
    }
    if(!this.pessoa.dataNascimento)
    {
        this.toastr.showMessage("Data de Nascimento Obrigatório")
        return false;
    }
    //...
    return true;
}

I was giving a study on this issue, to decrease the amount of if/else but I couldn’t fit into my scenario. How can I reduce them?

  • 1

    https://codesandbox.io/s/goofy-ptolemy-dl81e?file=/src/index.js, have a look!

3 answers

3


You can create a function responsible for validating the obligation, which displays the error and returns false if the field is invalid.

And a second function that will call the first one for each of the required fields. See the example below, adapted to run in Snippet.

function verificaCampoObrigatorio(valor, nomeCampo) {
  if (!valor) {
    console.log(`${nomeCampo} Obrigatório`);
    return false;
  }
  return true;
}

function verificarObrigatorios(pessoa) {
  return verificaCampoObrigatorio(pessoa.nome, 'Nome')
    && verificaCampoObrigatorio(pessoa.cpf, 'CPF')
    && verificaCampoObrigatorio(pessoa.dataNascimento, 'Data de Nascimento');
}

console.log('{}');
const return1 = verificarObrigatorios({});
console.log('{ nome: "Romeu" }');
const return2 = verificarObrigatorios({ nome: 'Romeu' });
console.log('{ nome: "Romeu", cpf: "123" }');
const return3 = verificarObrigatorios({ nome: 'Romeu', cpf: '123' });
console.log('{ nome: "Romeu", cpf: "123", dataNascimento: new Date() }');
const return4 = verificarObrigatorios({ nome: 'Romeu', cpf: '123', dataNascimento: new Date() });

console.log('--------------');
console.log('Retornos:', return1, return2, return3, return4);

This way, messages keep being displayed, only displays a single error message (because of return false, as in the question code) and if all are correct, returns true.

3

If you’re going to use something like @placementw mentioned, but want to get the boolean result, you could use the OR function. This would also show more than one message in case of multiple errors.


isCampoInvalido(campo: any, mensagem: String): boolean {
    if (campo != null) {
      return false;
    }
    this.toastr.showMessage(mensagem)
    return true;
}

verificarObrigatorios(): boolean {
  let invalido = false;
  invalido |= isCampoInvalido(this.pessoa.nome, "Nome Obrigatório");
  invalido |= isCampoInvalido(this.pessoa.cpf, "CPF Obrigatório");
  invalido |= isCampoInvalido(this.pessoa.dataNascimento, "Data de Nascimento Obrigatório");
  return !invalido;
}
  • Legal solution. To stay the way desired by the OP, I believe it would be more appropriate to use ||= as an operator, and return !invalido. And I recommend using unknown instead of any

1

I believe that something in this format would work the way you expect, just call the function for each field, being able to go through the object testing each property, if there are many, to save some lines

var camposSaoValidos = true;

function verificaCampo(campo: any, mensagem: String) {
  if (campo == null) {
    this.toastr.showMessage(mensagem)
    camposSaoValidos = false
  }
}

function verificarObrigatorios() {
  camposSaoValidos = true
  verificaCampo(this.pessoa.nome, 'nome nao existe');
  // chamar todos as verificações
  return camposSaoValidos
}

I edited to correct an error I made in Stackblitz, and adapt behavior as @Inkeliz pointed out

  • 2

    In that case the function verificarObrigatorios would always return true.

  • @Inkeliz is right, I had not paid attention to this part of the behavior, I edited to adjust. Thanks for the observation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.