3

I have a website with an existing form, that submits an email address to a third party website (example.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://example.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?

0

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used this solution and added boolean return values. This prevents posting the form if the validation fails when using 'onclick="return doSubmit();"'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.