[英]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.
如果我在年龄文本框中输入的数字大于100,它将显示错误消息并停留在当前表单页面。
However, if I use a variable errorMessage as the following to show the alert box, it doesn't work. 但是,如果我使用变量errorMessage如下所示来显示警报框,则它不起作用。 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 != "") :-) 我把它缩短了一点,但是您的主要问题是在if(errorMessage!=“”):-)之后没有括号
Your error is syntax as the others have pointed out... you are missing the { after the if statement. 您的错误是语法,正如其他人指出的那样...您在if语句后缺少{。 You may want to consider copying future code and pasting it into an online javascript syntax checker.
您可能需要考虑复制将来的代码并将其粘贴到在线javascript语法检查器中。 Eg http://www.javascriptlint.com/online_lint.php
例如http://www.javascriptlint.com/online_lint.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.