[tmbchr]™

Javascript Form Validation?



Is anybody out there good with javascript? I need to set up a simple form validation on my contact form, and for whatever reason, I can’t get it to work properly. I just want it to check to make sure that 4 out of the 5 form fields have a value entered, and if they don’t then show an alert box with the names of missing fields. If anybody could point me towards (or write me) a simple script that will do this (and only this, I don’t need anything else fancy), I’d be very grateful. Let me know either here in the comments, or drop me an email.

PS. I think my comments can accept coding examples as long as you wrap them in a < code > tag (minus the spaces).







6 Reader Responses

  1. davee Says:

    Something like this seems to work for me:

    <SCRIPT TYPE="text/javascript">

    function validate_form ( )
    {
    error = false;
    error_string = "Please fill in these field(s):";

    if ( document.contact.name.value == "" )
    {
    error = true;
    error_string = error_string + " name";
    }
    if ( document.contact.email.value == "" )
    {
    error = true;
    error_string = error_string + " email";
    }
    if ( document.contact.subject.value == "" )
    {
    error = true;
    error_string = error_string + " subject";
    }
    if ( document.contact.comments.value == "" )
    {
    error = true;
    error_string = error_string + " comments";
    }

    if (error == true)
    {
    alert (error_string);
    }

    return (!error);
    }

    </SCRIPT>

    and don’t forget to change the form tag to include an onsubmit:

    <form action="formmail.php" method="post" name="contact" id="contact" onsubmit="return validate_form()">

  2. mike oliver Says:


    function checkForm()
    {
    flag = "off"
    msg = "Please fill in the following missing fields:"
    formObj = document.forms[0]
    numFields = formObj.length - 1

    for(i=0; i< numFields;i++)
    {
    if(formObj.elements[i].value == "")
    {
    if (formObj.elements[i].name != "website")
    {
    msg = msg + "\n - " + formObj.elements[i].name
    flag = "on"
    }
    }
    }

    if (flag == "on")
    {
    alert(msg)
    return false;
    }
    }

  3. mike oliver Says:

    Oops… forgot that tag you mentioned above

    And as Davee said… don’t forget to amend the form tag to include an onSubmit()

  4. Tim Boucher Says:

    AHHH… that did the trick. Much much simpler than the stuff I was trying to do. I really need to brush up on this stuff.

    Thank you very much!

  5. Tim Boucher Says:

    ooh, wait, i only saw davee’s. let me try mikes. I love that little array action.

  6. Tim Boucher Says:

    PS. If anybody’s having trouble posting code, don’t worry about it. I’ve got this all figured out.

    But just FYI, it seems that the Wordpress commenting system filters out the script tag unless you replace the angle brackets with their & lt; style equivalents



SURROUND YOURSELF WITH STRENGTH.