简体   繁体   中英

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?

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

    if( errorMessage !== "" ){
        alert(errorMessage);
        return false;
    } else {
        return true;
    }
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 != "") :-)

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. Eg http://www.javascriptlint.com/online_lint.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM