Home > Software design >  If else and switch case alternative in Javascript
If else and switch case alternative in Javascript

Time:11-24

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;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related