Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!