简体   繁体   中英

I want to know how to do form validation in javascript

I am trying to learn form validation and its not working.

// 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;

//this is how I have created the form:

<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");

Use if statement like this and try

and check the variable x , if it is taking the value user entered correctly. Simply put alert for x variable and confirm it first

Your if statement condition, x != (>1900 &&<=2012) , makes no sense. >1900 and <=2012 do not evaluate to booleans, so you can't use the && operator on them. What you want is something like this:

x<1900 || x>2012

This checks if x is too low or too high, then uses the || (or) operator to check whether x is invalid in either way.

There are some syntax issues with your code. If you want get value of the birthyear input. You don't have to iterate over elements in form (as you do using for loop), you can do so: document.forms[0].elements['birthyear']

Also when you get a value of input element it type is string. And before comparing it to a value with integer type, you should convert string to integer:

intValue = parseInt(stringValue, 10);

So you code will be following

<form action="fake.php">Username
    <input class="required" type="text" name="username" id="username" />Birthyear
    <input class="required" type="number" name="birthyear" id="birthyear" />
    <input type="submit" />
</form>

<script>
// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
window.onload = function () {
    document.forms[0].onsubmit = function () {

        var birthYearElem = document.forms[0].elements['birthyear'],
            stringValue = birthYearElem.value,
            intValue = parseInt(stringValue, 10);

        if (intValue < 1900 || intValue > 2012) {
            alert("Must be between 1900 and 2012");
            birthYearElem.style.color = "yellow";
            return false;
        }
    }
}
<script>

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