Form validation with Javascript - Field value must

2019-08-30 12:59发布

问题:

I have a form on a page. On the form there is a field named Birthyear. I need to figure out the following in javascript:

When a value between 1900-2012 is entered into the field, the form are accepted. If value is not between 1900-2012, the Birthyear text box background color turn yellow.

Does anyone know how to achieve this?

My HTML is as follow:

</head><body>

<div id="div1">
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="post">
Username:   <input type="text" id="username" name="username"><br>         
Birth Year: <input type="text" id="birthYear" name="birthYear"><br><br>
<input type="submit"  value="Submit">
</form>

</div>

<div id="div2">
<img src="cat.jpg"    id="im1" name="image1"/>
<img src="dog.jpg"    id="im2" name="image2"/>
<img src="fish.jpg"   id="im3" name="image3" class='double'/>
</div>


</body></html>

My JS is as follow:

document.getElementById("username").focus();
function validateForm(){
var x=document.forms["myForm"]["username"].value;

if (x==""){
alert("Username Required!");
document.getElementById("username").focus();
}


var dob = document.forms["myForm"]["birthYear"];
var y = dob.value;


if(isNaN(dob)){
    alert('must be a number');
    dob.select();
    return false;

}

}

回答1:

function validateForm(){
var x=document.forms["myForm"]["username"].value;

if (x==""){
alert("Username Required!");
document.getElementById("username").focus();
}


var dob = document.forms["myForm"]["birthYear"];
var y = dob.value;

if(!isNaN(y)){

if(y>=1900 && y<=2012) {
    //Correct
 } else {
     //Wrong
     document.getElementById("birthYear").style.background= "yellow";
     document.getElementById("birthYear").focus();
     return false;
 }
} else {
  alert('must be a number');
}
}