Validate form with Javascript using onsubmit

I have a website with an existing form that sends an email address to a third party website (foo.com). Now I would like to check the email input field before submitting the form 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 Entry Field

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

Current 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 press the submit button, the form will be submitted and my Javascript seems to be ignored. What am I doing wrong?

+3
source share
1 answer

, "submit()", , "onsubmit" .

:

function doSubmit() {
  if (formCheck()) document.myForm.submit();
}
+3

Source: https://habr.com/ru/post/1735464/


All Articles