Return to Snippet

Revision: 38753
at January 7, 2011 02:55 by BrunoDeBarros


Initial Code
(function ($) {
    $.fn.forceNumeric = function () {
        return this.each(function () {

            $(this).keyup(function() {
                if (!/^[0-9]+$/.test($(this).val())) {
                    $(this).val($(this).val().replace(/[^0-9]/g, ''));
                }
            });
        });
    };
})(jQuery);

// Usage example: $('input.numeric').forceNumeric();

Initial URL
http://terraduo.com

Initial Description
This tiny jQuery plug in forces a user to enter only numeric values on an input field by silently removing non-numeric values as they're entered. (Caution: Never rely on client-side validation; use server-side validation as well)

Initial Title
Force an input to be numeric with jQuery

Initial Tags
javascript, jquery, validation

Initial Language
JavaScript