0

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;

}

}
2
  • Use parseInt(y) to get the value of the year, then check if it's between 1900 and 2012. Commented Mar 21, 2013 at 7:46
  • btw you have mistake, it is isNaN(y) and not dob. Dob is dom element. Commented Mar 21, 2013 at 7:54

1 Answer 1

0
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');
}
}
Sign up to request clarification or add additional context in comments.

3 Comments

you should move if else with y outside of isNaN if because if user enter any numeric value additional check will not be done.
Hi there,thank you so much for your help. The code makes sense, but for some reason it still doesn't work. Any idea why?
@user2147761 Sorry, i forgot to add not operator "!" in isNaN() condition. Now the example works. Thanks for pointing it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.