2012-12-05 107 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);