2012-12-05 109 views
0

我想使用jQuery来限制所有输入字段(电子邮件除外)的特殊字符,并限制ID允许的字符数。jQuery限制特殊字符和限制字段数

因此,例如,ID为“middleinitial”的输入字段只允许一个字符,并且该字符必须是字母数字,其中ID为“firstname”的字段最多允许50个字符,并且必须是字母和字段ID“zip”必须是数字,并且只允许5个字符。

我发现jQuery字母数字插件不再支持和Trey Hunner在stackoverflow上的替换(我知道其他帖子),但我没有找到足够的文档来实现,因为我是jQuery的新手。

任何帮助将不胜感激。

+0

http://bassistance.de/jquery-plugins/jquery-plugin-validation /是用于表单字段验证的插件。祝你好运! –

回答

0

我决定在HTML中对“maxlength”进行硬编码,并使用Trey Hunner对字母数字jQuery插件的更新。我不得不追捕一些文档,所以我添加了一个的jsfiddle帮助别人谁碰到这个情况与同一个问题:

http://jsfiddle.net/QX76h/3/

http://treyhunner.com/2010/10/replacement-for-jquery-alphanumeric-plugin/

(function ($) { 
    jQuery.fn.alphanumeric = function(r) { 
     alphanumericHelper(this, r, true, true); 
    }; 
    jQuery.fn.numeric = function(r) { 
     alphanumericHelper(this, r, false, true); 
    }; 
    jQuery.fn.alpha = function(r) { 
     alphanumericHelper(this, r, true, false); 
    }; 
    var alphanumericHelper = function(obj, restraints, alpha, numeric) { 
     var regex = ""; 
     if (numeric) 
      regex += "0-9"; 
     if (alpha) { 
      if (restraints == undefined || !restraints.allcaps) 
       regex += "a-z"; 
      if (restraints == undefined || !restraints.nocaps) 
       regex += "A-Z"; 
     } 
     if (restraints != undefined && restraints.allow != undefined) 
      regex += RegExp.escape(restraints.allow); 

     $(obj).regexRestrict(RegExp("[^"+regex+"]", "g")) 
    }; 
})(jQuery); 

/* 
* Function created by Colin Snover in response to an article by Simon Willison 
* on Regular Expression escaping in JavaScript: 
* http://simonwillison.net/2006/Jan/20/escape/ 
*/ 
RegExp.escape = function(text) { 
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
}; 

/* 
* Every time the form field is changed, sanitize its contents with the given 
* function to only allow input of a certain form. 
*/ 
(function ($) { 
    var inputEvents = "input"; 
    if (!("oninput" in document || "oninput" in $("<input>")[0])) { 
     inputEvents += " keypress keyup"; 
    } 

    jQuery.fn.restrict = function(sanitizationFunc) { 
     $(this).bind(inputEvents, function(e) { 
      var val = $(this).val(); 
      var sanitizedVal = sanitizationFunc(val); 
      if (val != sanitizedVal) { 
       $(this).val(sanitizedVal); 
      } 
     }); 
    }; 

    /* 
    * Every time the form field is changed, modify its contents by eliminating 
    * matches for the given regular expression within the field. 
    */ 
    jQuery.fn.regexRestrict = function(regex){ 
     var sanitize = function(text) { 
      return text.replace(regex, ''); 
     }; 
     $(this).restrict(sanitize); 
    } 
})(jQuery);