我正在尝试学习表单验证,但它不起作用。
// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
window.onload = function() {
document.forms[0].onsubmit = function() {
for(i = 0; i < document.forms[0].elements.length; i++){
var x =
document.forms[birthyear].value
if (x != (>1900 &&<=2012)){
alert("Must be between 1900 and 2012");
x.this.style.color ="yellow";
return false;
//这就是我创建表单的方式:
<form action = "fake.php"></br>
Username
<input class ="required"type = "text" name = "username" id ="username" /><br>
Username
<input class = "required"type = "text" name ="username"id ="username"/> <br>
Birthyear
<input class = "required" type = "number" name = "birthyear" id= "birthyear"/>
<input type = "submit"/>
</form>
最佳答案
if(x<1900 || x> 2012){
alert("invalid year");
使用这样的 if 语句并尝试
并检查变量 x 是否采用用户正确输入的值。 只需对 x 变量发出警报并首先确认
关于javascript - 我想知道如何在 javascript 中进行表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333125/