January 12th, 2007

A very fast way to validate a form with JavaScript

There are many universal form validation functions out there. But I created this very quick function to very easily check for input, without modifying your form fields in any way, and without have to check each field individually. The script just checks for a value, it doesn't validate the format (like an email address), because that's very easy to add, so you can do it yourself!

All you do is put the name of each field in the array, and it quickly loops through the array, checks the field, and fails if one of the fields is empty

function checkForm() {
        f = document.form1;
        var isGood = true;
       
        var required = new Array();
         required[0] = "email";
         required[1] = "password";
         required[2] = "first_name";
         required[2] = "last_name";
         required[3] = "country";
       
        for(i in required) {
                if(f.elements[i].value=="") {
                        isGood = false;
                        break;
                }
        }
       
        if(!isGood)
                alert("Please fill in all of the required fields.");
       
        return isGood;
}
//–>
</script>

Then put this in your form code:

<form name="form1" method="post" action="" onSubmit="return checkForm();">

6 Responses to ' A very fast way to validate a form with JavaScript '

Subscribe to comments with RSS or TrackBack to ' A very fast way to validate a form with JavaScript '.

  1. Eric said,

    on March 1st, 2007 at 12:56 pm

    how do i work this thing???

  2. Eric said,

    on March 1st, 2007 at 1:01 pm

    i also forgot to ask you if this would work on a game sight

  3. Justin Cook said,

    on March 1st, 2007 at 1:07 pm

    It would work on any site. As explained above, just include the code and reference it in your form. It's that simple!

  4. Eric said,

    on March 1st, 2007 at 3:17 pm

    i'm sorry but can you explain how to set up a form for a game that already exists, like runescape, thx

  5. Justin Cook said,

    on March 1st, 2007 at 3:30 pm

    If you don't know how to create an HTML form, you may need to search online for a basic HTML tutorial, sorry

  6. gregory said,

    on January 9th, 2008 at 2:17 pm

    I see the script ending tag, i was wondering where does the script start.
    where is your beginning tag

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image