0

Could someone explain why this code behaves incorrectly. My aim to to have a form that suppresses the submission if the name is not entered, or if a non signed integer is inputted for the age. I have logged the isInteger and more than zero comparisons and they both appear false so I cannot understand why the 'alert("Please enter a valid age.");' is not being executed in the OR statement.

I hope I haven't missed something obvious as I have trying to debug this for an hour now.

Any help would be appreciated

<!DOCTYPE html>
<html lang="en">

<head>
  <title>JavaScript Practice</title>
  <meta charset="utf-8">
  <style>
    input {
      display: block;
      margin-bottom: 1em;
    }
    
    label {
      float: left;
      width: 5em;
      padding-right: 1em;
      text-align: right;
    }
    
    #submit {
      margin-left: 7em;
    }
  </style>
  <script>
    function validateForm() {
      if (document.forms[0].userName.value == "") {
        alert("Name field cannot be empty.");
        return false;
      }
      console.log(Number.isInteger(document.forms[0].userAge.value));
      console.log(document.forms[0].userAge.value < 0;
        if (!Number.isInteger(document.forms[0].userAge.value) ||
          document.forms[0].userAge.value < 0) {
          alert("Please enter a valid age.");
          return false;
        }
        if (document.forms[0].userAge.value < 18) {
          alert("Age is less than 18. You are not an adult.");
          return false;
        } // end if
        alert("Name and Age are valid.");
        return true;
      } // end function validateForm
  </script>
</head>

<body>
  <h1>JavaScript Form Handling</h1>
  <form method="post" action="http://webdevbasics.net/scripts/demo.php" onsubmit="return validateForm();">
    <label for="userName">Name:</label>
    <input type="text" name="userName" id="userName">
    <label for="userAge">Age:</label>
    <input type="text" name="userAge" id="userAge">
    <input type="submit" value="Send information" id="submit">
  </form>
</body>

</html>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Mysa Mysa
  • 19
  • 1
  • 5
  • why don't u use a [required attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required) ? – Mister Jojo Sep 23 '21 at 20:47

1 Answers1

1

Tried running the code in the browser.

I've got the following error:

Uncaught SyntaxError: missing ) after argument list  index.html:31:59

The issue was in line 31 where ) was missing:

console.log(document.forms[0].userAge.value < 0);

After this fix I was getting Please enter a valid age. for any age.

The issue was in Number.isInteger() function, which checks for an argument being an integer and always returns false because userAge.value is a string.

The check you need here is if the string is a valid number, you can see this answer for all the details, but one suggested method is to use parseInt(string, radix) function (radix argument is optional but it's safer to specify 10):

const ageInt = Number.parseInt(document.forms[0].userAge.value, 10);

parseInt converts a string to a number, ageInt will be NaN if userAge.value is a string which is not a valid number.

So using ageInt and Number.isNaN() check for NaN the condition can be rewritten as:

const ageInt = Number.parseInt(document.forms[0].userAge.value, 10);
console.log(ageInt);
console.log(ageInt < 0);
if (Number.isNaN(ageInt) || ageInt < 0) {
    alert("Please enter a valid age.");
    return false;
}

You can find the whole updated code bellow:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>JavaScript Practice</title>
    <meta charset="utf-8">
    <style>
        input {
            display: block;
            margin-bottom: 1em;
        }

        label {
            float: left;
            width: 5em;
            padding-right: 1em;
            text-align: right;
        }

        #submit {
            margin-left: 7em;
        }
    </style>
    <script>
        function validateForm() {
            if (document.forms[0].userName.value == "") {
                alert("Name field cannot be empty.");
                return false;
            }
            const ageInt = Number.parseInt(document.forms[0].userAge.value, 10);
            console.log(ageInt);
            console.log(ageInt < 0);
            if (Number.isNaN(ageInt) || ageInt < 0) {
                alert("Please enter a valid age.");
                return false;
            }
            if (ageInt < 18) {
                alert("Age is less than 18. You are not an adult.");
                return false;
            } // end if
            alert("Name and Age are valid.");
            return true;
        } // end function validateForm
    </script>
</head>

<body>
    <h1>JavaScript Form Handling</h1>
    <form method="post" action="http://webdevbasics.net/scripts/demo.php" onsubmit="return validateForm();">
        <label for="userName">Name:</label>
        <input type="text" name="userName" id="userName">
        <label for="userAge">Age:</label>
        <input type="text" name="userAge" id="userAge">
        <input type="submit" value="Send information" id="submit">
    </form>
</body>

</html>
Vitalii
  • 2,071
  • 1
  • 4
  • 5