如何在Jquery中的文本框中添加验证

时间:2014-06-12 07:16:27

标签: php jquery

我需要什么:

  • 当用户在文本框中输入邮件地址时,逗号(,)应该包含电子邮件地址。

    我使用了jquery自动填充示例,这里是网址:http://jqueryui.com/autocomplete/#multiple

  • 我希望该用户在文本框中输入多个电子邮件地址,并且(,)应该分隔每个电子邮件地址。

    • 这是我想要的快照:http://postimg.org/image/z7tv89bab/

       $(function() {
       var availableTags = [
       "af@gmail.com",
       "af1@gmail.com",
      "af2@gmail.com",
      "af3@gmail.com",
      
       ];
      function split( val ) {
       return val.split( /,\s*/ );
       }
      function extractLast( term ) {
      return split( term ).pop();
      }
      
      $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
       if ( event.keyCode === $.ui.keyCode.TAB &&
       $( this ).data( "ui-autocomplete" ).menu.active ) {
       event.preventDefault();
      }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
        // delegate back to autocomplete, but extract the last term
         response( $.ui.autocomplete.filter(
        availableTags, extractLast( request.term ) ) );
        },
       focus: function() {
       // prevent value inserted on focus
        return false;
        },
        select: function( event, ui ) {
       var terms = split( this.value );
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        // add placeholder to get the comma-and-space at the end
         terms.push( "" );
        this.value = terms.join( ", " );
         return false;
        }
       });
      });
      

        标签编程语言:     

1 个答案:

答案 0 :(得分:1)

尝试使用jquery验证插件来验证文本框。

//接受多封邮件的代码

jQuery.validator.addMethod("multiemail", function (value, element) {
    if (this.optional(element)) {
        return true;
    }

    var emails = value.split(','),
        valid = true;

    for (var i = 0, limit = emails.length; i < limit; i++) {
        value = emails[i];
        valid = valid && jQuery.validator.methods.email.call(this, value, element);
    }

    return valid;
}, "Invalid email format: please use a comma to separate multiple email addresses.");

上述功能应该用于验证js

var validator = $("#frmlogin").validate({
    errorElement: 'div',
    rules: {
        email: {
            required: true,
            email: true,
            multiemail: true
        }
    });