Search code examples
javascripthtmlvalidationarithmetic-expressions

Input validation only working once


I am trying to create a script that will take 2 inputs and calculate the sum. I would like both inputs to be validated before the calculation takes place - inputs must range between 0 and 10.

However when I input values over 10 in both fields (e.g. 50), I am only getting one validation error instead of two.

What could be wrong?

     function calc() {
    var x, y, z, text1, text2;   
    // Get the value of the input field with id="numb"
       x = Number(document.getElementById("val01").value);
       y = Number(document.getElementById("val02").value);

       // If x is Not a Number or less than one or greater than 10
       if (isNaN(x) || x < 0 || x > 10) {
         text1 = "Input not valid";
         document.getElementById("validation1").innerHTML = text1;
       } else if (isNaN(y) || y < 0 || y > 10) {
         text2 = "Input not valid";
         document.getElementById("validation2").innerHTML = text2;
       } else {
         z = x + y;
         document.getElementById("total").innerHTML = z;
       }

     }
  
    
    <p>Please input a number between 0 and 10:</p>
    
    1st number:<input id="val01" required> <b id="validation1"></b> <br> 
    2nd Number:<input id="val02" required> <b id="validation2"></b> <br>

    <button onclick="calc()">click</button><br /> sum = <span id="total">0</span>
   


Solution

  • If your first validation fails (if (...)), you do not execute the second validation (else if (...)) anymore.

    Instead, run the validations separately from each other and only do the calculation if both succeed, e.g.:

    function calc() {
        var x, y, z, text1, text2;
        // Get the value of the input field with id="numb"
        x = Number(document.getElementById("val01").value);
        y = Number(document.getElementById("val02").value);
    
        var valid = true;
    
        // If x is Not a Number or less than one or greater than 10
        if (isNaN(x) || x < 0 || x > 10) {
            text1 = "Input not valid";
            document.getElementById("validation1").innerHTML = text1;
            valid = false;
        }
    
        if (isNaN(y) || y < 0 || y > 10) {
            text2 = "Input not valid";
            document.getElementById("validation2").innerHTML = text2;
            valid = false;
        }
    
        if(valid) {
            z = x + y;
            document.getElementById("total").innerHTML = z;
        }
    
    }