0

我正在尝试使用 jQuery 来限制所有输入字段的特殊字符(除了 email ),并且还限制了 ID 允许的字符数。

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

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

任何帮助将不胜感激。

4

1 回答 1

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);
于 2012-12-05T21:18:03.110 回答