如何在启用“提交”按钮之前动态测试输入字段以获取格式正确的电子邮件地址

时间:2013-05-29 03:53:28

标签: jquery forms input filter email-validation

我为电子邮件注册表单编写了以下jQuery代码。

$(document).ready(function () {
  var default_value = '<?php echo $email_text ?>';
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  $('#email').each(function () {
    $(this).focus(function () {
      if (this.value == default_value) {
        this.value = '';
      }
    });
  $(this).blur(function () {
    if (this.value == '') {
      this.value = default_value;
    }
  });
});
$('button#yes').hover(function () {
  $(this).css('background', '#fff').css('cursor', 'not-allowed');
  $('#email').css('background', '#ca9822');
}, function () {
  $(this).css('background', '').css('cursor', '');
  $('#email').css('background', '');
});
$('#email').keyup(function () {
  if (this.value.length > 2 && this.value !== default_value && filter.test(this)) {
    $('button#yes').unbind().css('background', '').css('cursor', '').click(function () {
      showconfirm();
    });
    $('#email').css('background', '');
  } else {
    $('button#yes').unbind().hover(function () {
      $(this).css('background', '#fff').css('cursor', 'not-allowed');
        $('#email').css('background', '#ca9822');
      }, function () {
        $(this).css('background', '').css('cursor', '');
        $('#email').css('background', '');
      });
    }
  });
$("form#signupform").submit(function () {
. . .

它基本上做的是检查输入表单,然后启用“是”按钮,然后触发showconfirm()功能,这会打开一个真实的提交按钮,最终处理提交行动等。

问题是我只需要条款和“的确认”按钮。隐私政策问题。我真的想在第一个按钮上完成整个检查过程。我的意思是如果输入的电子邮件不符合某些标准,用户不应该单击“是”。我可以让它工作到value.length > 2(我在另一篇SO文章中读到,电子邮件的最小长度可以是3个字符,即“a @ b”......这就是> 2来自,如果你想知道的话),直到value !== default_value(默认值基本上是“你的电子邮件”,它从输入字段清除,重新绘制在输入字段中,用户在输入任何自定义数据之前对输入进行聚焦和模糊处理)。但是当我加入filter.test()时,我总是得到false

我肯定在这里弄错了,虽然我无法弄明白。我之前在submit函数下使用它,它运行得很好。但是,正如我所说的那样,我正试图在流程的第一部分完成所有工作。实际上,在submit函数中,这最终会成为重复代码等麻烦,添加错误消息等等等。这就是我想要切换它的原因。

请问任何想法?

1 个答案:

答案 0 :(得分:0)

您正在尝试测试输入元素上的模式,而不是测试其值。 试试这个:

$('#email').keyup(function () {
  if (this.value.length > 2 && this.value !== default_value && filter.test(this.value)) {

您尝试filter.test(this),但应使用filter.test(this.value)