简体   繁体   English

JavaScript电子邮件验证代码问题(仍在提交表单)

[英]Javascript email validation code issue (still submitting the form)

I have added some javascript to my form to validate the email before submitting the form. 我已经在表单中添加了一些JavaScript,以在提交表单之前验证电子邮件。 I dont want a seperate button to validate, i want it to be part of the form submit button. 我不希望使用单独的按钮进行验证,我希望它成为表单提交按钮的一部分。 It works currently and a message comes up asking me to put a valid email address in. The problem is when i click "ok" it still tries to submit the form (and fails) instead of returning to the form to correct the email addres. 它当前可以正常工作,并且出现一条消息,要求我输入有效的电子邮件地址。问题是,当我单击“确定”时,它仍然尝试提交表单(失败),而不是返回表单来更正电子邮件地址。

My Javascript: 我的Javascript:

<script language="javascript">

function checkEmail() {

var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
 }
}</script>

My HTML: 我的HTML:

<input type="text" name="email" id="txtEmail" />
<input type="SUBMIT" class="button" value="Submit Email" onclick='Javascript:checkEmail();' />

I cant figure out what the problem is. 我不知道是什么问题。 Any help would be appreciated. 任何帮助,将不胜感激。 Cheers 干杯

只需在函数调用之前添加return即可:

<input type="SUBMIT" class="button" value="Submit Email" onclick='Javascript:return checkEmail();' />

Try this: 尝试这个:

HTML: HTML:

<form name="whatever" action="action.asp" onsubmit="return validateForm()" method="post">
    <input type="text" name="email" id="txtEmail" />
    <input type="SUBMIT" class="button" value="Submit Email" />
</form>

JS (pseudocode) JS(伪代码)

function validateForm()
{
    if (something) {
        alert('validation failed');
        return false;
    }
}

Here is the rework of your code. 这是代码的返工。

<script type="text/javascript">
    function checkEmail() {
        var email = document.getElementById('txtEmail');
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

        if (!filter.test(email.value)) {
            alert('Please provide a valid email address');
            email.focus;
            return false;
        }
    }
</script>

<input type="text" name="email" id="txtEmail" />
<input type="SUBMIT" class="button" value="Submit Email" onclick='checkEmail();' />

Works as expected. 可以正常工作。

There is not a major problem, the function is working fine but it is not returning back, just add return before you call the function, here is the example below: 没什么大问题,该函数可以正常工作,但是它不会返回,只需在调用该函数之前添加return即可,这是下面的示例:

    <input type="SUBMIT" class="button" value="mail" onclick='Javascript:return  checkEmail();' />

This will sort out your problem, enjoy :) 这将解决您的问题,请享受:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM