views:

136

answers:

1

I have a website with an existing form, that submits an email address to a thirdparty website (foo.com). Now I'd like to validate the email input-field before submitting the form by using Javascript.

My Javascript

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function formCheck() {
    // Fetch email-value
  sEmail = document.myForm.recipientEmail.value ;
    // value empty?
    if (sEmail == 0)
        {
            alert('Enter Email-Address.');
            return false;
        }
    else
        {
            // value valid?
            if (!isValidEmailAddress(sEmail))
                {
                    alert('Enter valid Email-Address.');
                    return false;
                }
            else
                {
                    return true;
                }
        }
}   

Existing form tag

<form name="myForm" action="http://foo.com" method="post" onsubmit="return formCheck();">

Existing email input field

<input type="text" class="form-text" name="email" id="recipientEmail">

Existing submit button

<input type="image" src="some_pic.gif" alt="OK" id="submit_form" onclick="document.onlineForm.submit();" value="send" name="submit_button"> 

Now, as soon as I hit the submit button, the form is submitted and my Javascript seems to be ignored. What am I doing wrong?

+3  A: 

When you submit the form by calling "submit()" directly, like your button is doing, the "onsubmit" handler is not called.

You could have the submit button call a different function:

function doSubmit() {
  if (formCheck()) document.myForm.submit();
}
Pointy
I used this solution and added boolean return values. This prevents posting the form if the validation fails when using 'onclick="return doSubmit();"'.
Javier