正整数和小数的正则写成自定义插件

正整数: /[^0-9]/g, ''
decimal: /[^0-9.]/g, ''

 
然后可以写一个自定义插件:


(function ($) {
            $.fn.validatedigits = function (e) {
                this.val(this.val().replace(/[^0-9]/g, ''));
                if (e.which != 46 && (e.which < 48 || e.which > 57)) {
                    e.preventDefault();
                }
            };

            $.fn.validatedecimal = function (e) {
                this.val(this.val().replace(/[^0-9.]/g, ''));
                if ((e.which != 46 || this.val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
                    e.preventDefault();
                }
            };     
        }(jQuery));
Source Code

应用:

 $("#TextPort").on("input", function (evt) {
             $(this).validatedigits(evt);
        });
原文地址:https://www.cnblogs.com/insus/p/6558050.html