简体   繁体   中英

how to validate a simple form with javascript

Ok, what I am trying to do are several things:

  1. list errors above the form if any fields are blank
  2. have it highlighted in red if they are blank
  3. once the user tries to fix it, ie, filling the blank fields, to have the red highlights go away ... like do you do this with focus, onblur?

(also I'm a JS newbie, so I'm still struggling how to have a function implemented that does that all that ... you do use a function for this, correct?

Here's an earlier form of mine ... I am really struggling to implement those three characteristics listed above ... how do I implement those in the code beneath? Thanks in advance.

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Testy Form</title>
    </head>
    <body>
        <h4>Learning to Validate Forms</h4>
        <div id="validationErrors"></div>
        <form action="" method="post" id="testyForm">
            <label>Name
                <input type="text" name="name" value="" id="name">
            </label>
            <br /><br />
            <label>Email
                <input type="text" name="email" value="" id="email">
            </label>
            <br /><br />
            <input type="submit" value="Submit">
        </form>

        <script>

            var formy = document.getElementById('testyForm');

             var required_inputs = ['name', 'email'];
        formy.onsubmit = function(event) {
            for (var i = 0; i < required_inputs.length; i++) {
                var input = this[required_inputs[i]];
                if (input.value.length == 0) {
                    event.preventDefault(); 
                    input.style.border = "1px solid red";
                    input.style.backgroundColor = "#FFCCCC";
                }
            }
        }
        </script>
    </body>
    </html>

if you are just trying to get things work, I would suggest using a validation library instead of writing your own.

if you are learning Javascript, here's the error in your code:

update

var input = this[required_inputs[i]];

to

var input = document.getElementById(required_inputs[i]);

edit - explanation

you declared required_inputs as an array:

var required_inputs = ['name', 'email'];

and when you loop through it, required_inputs[i] will return 'name' and 'email' so that can be used as the parameter of getElementById() .

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