Help with javascript form validation

Posted by zac on Stack Overflow See other posts from Stack Overflow or by zac
Published on 2010-05-06T01:37:03Z Indexed on 2010/05/06 1:48 UTC
Read the original article Hit count: 284

Filed under:
|

I am getting a headache with form validation and hoping that the kind folks here can give me a hand finishing this sucker up

I have it basically working except the email validation is very simplistic (only alerts if it is blank but does not actually check it if is a valid email address) and I am relying on ugly alerts but would like to have it reveal a hidden error div instead of the alert. I have this all wrapped up with an age validation check too.. here are the important bits, minus the cookie scripts

    function checkAge()
          {

     valid = true;
     if ( document.emailForm.email.value== 0 )
            {
                    alert ( "Please enter your email." );
                    valid = false;
            }

     if ( document.emailForm.year.selectedIndex == 0 )
            {
                    alert ( "Please select your Age." );
                    valid = false;
            }

     var min_age = 13;
             var year = parseInt(document.forms["emailForm"]["year"].value);
             var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
             var day = parseInt(document.forms["emailForm"]["day"].value);
        var theirDate = new Date((year + min_age), month, day);
                var today = new Date;

                if ( (today.getTime() - theirDate.getTime()) < 0) {

                 var el = document.getElementById('emailBox');
                 if(el){
                        el.className += el.className ? ' youngOne' : 'youngOne';
                        }
                 document.getElementById('emailBox').innerHTML = "<img src=\"emailSorry.gif\">"
         createCookie('age','not13',0)
                    return false;
                }
                else {
//this part doesnt work either
 document.getElementById('emailBox').innerHTML = "<img src=\"Success.gif\">"
                    createCookie('age','over13',0)
                    return valid;
                };
            };

     var x = readCookie('age');
    window.onload=function(){
    if (x=='null')  {    

       };
    if (x=='over13')  {    

       };
    if (x=='not13')  {    
       document.getElementById('emailBox').innerHTML = "<img src=\"emailSorry.gif\">";
       };

       }

can someone please help me figure a better email validation for this bit:

if ( document.emailForm.email.value== 0 )
        {
                alert ( "Please enter your email." );
                valid = false;
        }

and how would I replace the alert with something that changes a class from hidden to visible? Something like?

document.getElementById('emailError').style.display='block'

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about form-validation