jQuery限制特殊字符和限制字段数

时间:2012-12-05 19:32:15

标签: jquery

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

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

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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);