skip to Main Content

I have an <input type="number /> that may or may not have min or max values set. If the user enters a number outside that range, I want to print an error message. I have the error handling figured out but I’m trying to find a "nicer" way to determine which error message to print.

if(!!min && !!max && (val < min || val > max)) {
    print(`Enter a number between ${min} and ${max}`);
} else if(!!min && val < min) {
    print(`Enter a number greater than ${min}`);
} else if(!!max && val > max) {
    print(`Enter a number less than ${max}`);
}

Is there a better way to structure this if/else block?

2

Answers


  1. how about this

    if ((!!min && val < min) || (!!max && val > max)) {
      let errorMessage = '';
    
      if (!!min && !!max) {
        errorMessage = `Enter a number between ${min} and ${max}`;
      } else if (!!min) {
        errorMessage = `Enter a number greater than ${min}`;
      } else if (!!max) {
        errorMessage = `Enter a number less than ${max}`;
      }
    
      print(errorMessage);
    }
    

    OR


    if(!!max && val > max) {
      print(`Enter a number less than ${max}`);
    } else {
      print(`Your number is ${val}`);
    }
    
    // Answer:
    if (min && max) {
      if (val < min || val > max) {
        print(`Enter a number between ${min} and ${max}`);
      } else {
        print(`Your number is ${val}`);
      }
    } else if (min && val < min) {
      print(`Enter a number greater than ${min}`);
    } else if (max && val > max) {
      print(`Enter a number less than ${max}`);
    } else {
      print(`Your number is ${val}`);
    }
    
    Login or Signup to reply.
  2. Slight variation when min/max are undefined when unset. This also avoids the 0 border case…

    if (val < min || val > max) {
      let errorMessage;
      if (max === undefined) {
        errorMessage = `Enter a number greater than ${min}`;
      } else if (min === undefined) {
        errorMessage = `Enter a number less than ${max}`;
      } else {
        errorMessage = `Enter a number between ${min} and ${max}`;
      }
      print(errorMessage);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search