0

我正在从头开始构建一个联系表单,其中包含一些简单但花哨的动画,如动画复选标记、动画发送按钮、mouseenter/mouseleave 动画字段等。同时我正在编写验证代码,但我遇到了一些困难电子邮件字段。我一直在查看其他帖子并在谷歌上搜索有用的信息,但我的上下文有点奇怪。这是代码:

// Check if the email address is valid
function checkValidEmailAddress(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][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
};

// Email field validation
$('#userEmail').blur(function(){
  $(this).animate({'background-color':'#ffffff'}, 200);
  if($.trim($(this).val()) == ""){
    emailInvalidation();
    $('#inputText_infoBox p').html('Não se esqueça do seu e-mail!');
  }
  else{
    emailValidation();
    $('#inputText_infoBox p').html('O endereço de e-email parece válido');
  }
});

如您所见,我正在对 blur() 进行验证,特别是检查该字段是否不为空 - 问题:如何在 blur 函数中将 checkValidEmailAddress 上下文化?我应该把它放在哪里以及如何放置?

谢谢你。

佩德罗

4

2 回答 2

1

我做了一个更容易扩展的替代解决方案。你可以在http://jsbin.com/eyimis/1/上看到它,这里的代码:http: //jsbin.com/eyimis/1/edit

一旦验证了所有输入,它还能够显示提交按钮。

var test = {
  // Email
  'email' : {
    'validate' : 0,
    'fn' : function(emailAddress) {
      var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return pattern.test(emailAddress);
    }
  },
  // First and last name
  'name' : {
    'validate' : 0,
    'fn' : function(name) {
      name = name.split(' ');
      // Does it contain two names?
      return name.length > 1 && name[1].length > 0;
    }
  }
}, $error = $('#inputText_infoBox p');

var ready = function () {
  // How many inputs do we have to validate?
  var inputs = $.map(test, function(n, i) { return i; }).length, score = 0;
  for(var key in test) {
    // If this input is validated, we have ourselves a score!
    if(test[key].validate === 1) {
      score++;
    }
    // Is the amount of scores equal to to amount of inputs?
    if(score === inputs) {
      return true; 
    }
  }
};

$('input[type=text]').on({
  /* We'll check against a validate function every time the user
  press a key, depending on what field the user is interacting with */
  keyup: function() {
    var $this = $(this);
    // Run the validate function for this particular input field
    if(test[$this.attr('id')].fn($this.val())) {
      // Validation returned true, yay! :)
      test[$this.attr('id')].validate = 1;
      $this.css({'background-color': '#00f000'});
      $error.html('');
    } else {
      // It returned false :(
      test[$this.attr('id')].validate = 0;
      $this.css({'background-color': '#ffffff'});
    }
    if(ready()) {
      $('#inputText_infoBox').after().html($('<input type="submit">'));
    } else {
      $button = $('input[type="submit"]');
      if(typeof $test !== undefined) {
        $button.remove();
      }
    }
  },
  /* We'll do the check for empty text fields on blur to
  avoid annoying errors */
  blur: function() {
    var $this = $(this);
    // Only run if input hasn't validated yet
    if(test[$this.attr('id')].validate === 0) {
      if($.trim($this.val()) === '') {
        $error.html('Empty field');
      }
      // The input got to be invalid!
      else {
       $error.html('Your ' + $this.attr('id') + ' is invalid'); 
      }
    } 
    // It validated, clear error messages 
    else {
      $error.html(''); 
    }
  }
});
于 2013-04-12T13:52:56.993 回答
0

您必须将它放在您的else语句中并将您的字段值作为参数传递;您的代码将如下所示:

$('#userEmail').blur(function(){
  $(this).animate({'background-color':'#ffffff'}, 200);
  if($.trim($(this).val()) == ""){
    $('#inputText_infoBox p').html('Não se esqueça do seu e-mail!');
  }
  else{
    // Here you are passing the field value to the checkValidEmailAddress
    // function, which will return true if the pattern is found, or false
    // if it is not.
    if( checkValidEmailAddress( $(this).val() ) ) 
         $('#inputText_infoBox p').html('O endereço de e-email parece válido');
    else 
         $('#inputText_infoBox p').html('O endereço de e-email parece inválido');
  }
});
于 2013-04-12T11:19:23.037 回答