检查HTML格式的电子邮件匹配

时间:2014-02-17 00:33:28

标签: javascript html

我有一个网页,用户提交的表单包含电子邮件字段和确认电子邮件字段。

如何检查以确保这两个字段完全相同?

<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用Javascript,因为你可以在它转到你的php文件之前停止表单提交。但是,验证使用php文件输入的数据以及有一些程序可以让您在进行javascript检查后更改表单中提交的数据仍然是一个好习惯。

<script>
    function checkMatch() {
        var email = document.getElementById('email').value;
        var emailConfirm = document.getElementById('emailConfirm').value;

        if (email != emailConfirm) {
            alert("Email addresses are not the same.");
            return false; //Returning 'false' will cancel form submission
        } else {
            /*
            place the return true; at the end of the function if you do other
            checking and just have if conditions and return them as false. If
            one thing returns false the form submission is cancelled.
            */
            return true;
        }
    }
</script>

并将表单更改为onSubmit

<form method="post" action="submit_query.php" onSubmit="checkMatch()">

将ID添加到您的电子邮件输入中,例如:email和emailConfirm。如果您愿意,可以更改它们,但仅举一例我使用过的。

答案 1 :(得分:0)

使用jQuery,但没有错误处理,我建议:

$('form').on('submit', function() {
    return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});

非常简单JS Fiddle demo

相关问题