Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
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;
}

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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;
}
over 4 years ago · Santiago Trujillo Denunciar

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
over 4 years ago · Santiago Trujillo Denunciar

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;
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda