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

226
Vistas
Using switch case to validate form

I am creating a form validation with 2 conditions to validate. Is this a good way to use switch case with if else statement? Or is this something that is frown upon? If so, what would a better way to approach this without using external library, thank you.

Code:

const validate = ( name, value) => {
   switch (name) {
   case "user_name":
if (!value) {
 setErrors({ ...errors, user_name: "Please, submit required data" });
 } else if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
 setErrors({
...errors,
 user_name: "Please, provide the data of indicated type(no special characters)",
});
 } else {
let newObj = omit(errors, "user_name");
 setErrors({ ...newObj });
 }
 break;
.....
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It's not very readable so I wouldn't say it's the best way, but it's definitely not the worst. You could try something like this.

const validate = (name, value) => {
  if (!value) {
    setErrors({ ...errors, [name]: "Please, submit required data" })
    return
  }
  
  switch (name) {
    case "user_name": {
      if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
        setErrors({
          ...errors,
          user_name: "Please, provide the data of indicated type(no special characters)"
        })
        return
      }
    }
  }
  
  const newObj = omit(errors, name)
  setErrors({ ...newObj })
}
about 4 years ago · Juan Pablo Isaza 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