A very fast way to validate a form with JavaScript

by CarcaBot on July 24, 2009 · 0 comments

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

Previous post:

Next post: