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

143
Visualizações
If else and switch case alternative in Javascript

Looking for an alternative to the conditional statement. As you can see from my code, the process is overly repetitious and disorganized. It will become increasingly difficult to maintain code as it grows in size. In order to avoid this situation, I'm looking for alternatives.

function validate(values) {
  let errors = {};
  //   Email Error
  if (!values.email) {
    errors.email = "Email address is required";
  } else if (!/\S+@\S+\.\S+/.test(values.email)) {
    errors.email = "Email address is invalid";
  }
  //   Password Error
  if (!values.password) {
    errors.password = "Password is required";
  } else if (values.password.length < 6) {
    errors.password = "Password must be 6 or more characters";
  }
  return errors;
}

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

0

You could move some logic into configuration. Try to harmonise checks such that they all depend on regular expressions. So for a minimum length of 6, use /....../ as regular expression. Also make sure the regular expression will not accept an empty string in case the field is considered required.

For example:

// All specifics are encoded here:
const checks = [
    { field: "email", regex: /^\S+@\S+\.\S+$/, name: "Email address", msg: "must be 6 or more characters" },
    { field: "password", regex: /....../, name: "Password", msg: "is invalid" },
];

// ...while this is now (more) generic:
function validate(values) {
    const errors = {};
    for (const {field, regex, name, msg} of checks) {
        if (!regex.test(values[field])) {
            errors[field] = name + " " + (values[field] ? msg : "is required");
        }
    }
    return errors;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Right now, the validate function is used for both passwords and emails.

However, this can be split into two functions, one for validating emails, and the other for validating passwords. This helps to decouple the action of validating emails from validating passwords, and makes debugging/maintaining easier.

Also, you can try ternary operators if you want to make your if-else clauses less cluttered.

function validate(values) {
    errors = {};
    errors.email = validate_email(values.email) == null
        ? null : validate_email(values.email);

    errors.password = validate_password(values.password) == null 
        ? null : validate_password(values.password);
  
    return errors;
}

function validate_email(email) {
    if (email == null) {
        return "Email address is required";
    } else if (!/\S+@\S+\.\S+/.test(values.email)) {
        return "Email address is invalid";
    } 
    
    return null;
}

//validate_password left as an exercise
about 4 years ago · Juan Pablo Isaza Relatório

0

You can access column in a js object by using myObject[nameOfYourColumn]

So we can think build a generic method like this

function validateColumn(object, columnName, format, errors) {
  if (!object[columnName]) {
       errors[columnName] = `${columnName} is required`;
  } else if (!format.test(object[columnName])) {
      errors[columnName] = `${columnName} is invalid`;
  }
}

your method will become

function validate(values) {
  let errors = {};
  //   Email Error
  validateColumn(values, 'email', '/\S+@\S+\.\S+/', errors);
  //   Password Error
  validateColumn(values, 'password', '/^.{6,}$/', errors);
  return errors;
}
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