tonga
tonga

Reputation: 11981

JavaScript form validation: Why does the first work but the second doesn't?

I have the following form:

<form action="next.html" id="userInput" method="post" onsubmit="return validate();">
     Age: <input type="text" name="age" id="age"/>


function validate() {
            var age = document.getElementById("age").value;

            if(age > 100 || age < 0) {

                alert("Age must be within 0 and 100");
                return false;
            } else {
                return true;
            }

        }

This works as normal. If I enter a number in the age textbox great than 100, it will show the error message and stay at the current form page.

However, if I use a variable errorMessage as the following to show the alert box, it doesn't work. It will go to the next page without poping up the alert error message.

function validate() {
            var age = document.getElementById("age").value;

            var errorMessage="";
            if(age > 100 || age < 0) {
                errorMessage = "Age must be within 0 and 100";
            }


            if( errorMessage !== "" )
                alert(errorMessage);
                return false;
            } else {
                return true;
            }
        }

So why does the first work but the second doesn't?

Upvotes: 0

Views: 832

Answers (3)

James Oravec
James Oravec

Reputation: 20381

Your error is syntax as the others have pointed out... you are missing the { after the if statement. You may want to consider copying future code and pasting it into an online javascript syntax checker. E.g. http://www.javascriptlint.com/online_lint.php

Upvotes: 1

pwnyexpress
pwnyexpress

Reputation: 1016

function validate() {
        var age = parseInt(document.getElementById("age").value),
        errorMessage;

        if(age > 100 || age < 0) errorMessage = "Age must be within 0 and 100";
        if(errorMessage) {
            alert(errorMessage);
            return false;
        } 
        else {
            return true;
        }
    }

I shortened it a bit, but your main problem was not having a bracket after if(errorMessage != "") :-)

Upvotes: 3

Amit Yaron
Amit Yaron

Reputation: 654

I see a missing left brace after the condition. The code should be:

    if( errorMessage !== "" ){
        alert(errorMessage);
        return false;
    } else {
        return true;
    }

Upvotes: 5

Related Questions