Gregory Nozik
Gregory Nozik

Reputation: 3374

Check length of value and if it is numeric

I am using the following code to check if the value in a textbox is numeric:

(function ($) {
    $.fn.numeric = function (options) {
        return this.each(function () {
            var $this = $(this);

            $this.keypress(options, function (e) {
                // allow backspace and delete
                if (e.which == 8 || e.which == 0)
                    return true;

                //if the letter is not digit
                if (e.which < 48 || e.which > 57)
                    return false;

                // check max range
                var dest = e.which - 48;
                var result = this.value + dest.toString();
                if (result > e.data.max) {
                    return false;
                }
            });
        });
    };
})(jQuery);

When using on an input textbox element, I declare it as follows

$(input).numeric({ max: 999});

The problem is that it's working on input and checking that value should be integer and not string.

But I need to change code that it will validate double as well.

So if I will insert 0.22 it will be OK, but if I will insert .22 it will not populate the number.

Please help

Upvotes: 0

Views: 2107

Answers (5)

Gregory Nozik
Gregory Nozik

Reputation: 3374

I followed solution suggested by @Guillaume. But I added additional condition

 if (this.value.length > e.data.maxLength)
            return false;

So the all code below

(function ($) {

    $.fn.numeric = function (options) {

        return this.each(function () {
            var $this = $(this);

            $this.keypress(options, function (e) {

                // allow backspace and delete
                if (e.which == 8 || e.which == 0)
                    return true;

                if (e.which == 46 && this.value.length >= 1 && this.value.indexOf('.') == -1) {
                    return true;
                }
                //if the letter is not digit
                if (e.which < 48 || e.which > 57)
                    return false;

                // check max range
                var dest = e.which - 48;
                var result = this.value + dest.toString();
                if (result > e.data.max) {
                    return false;
                }

                if (this.value.length > e.data.maxLength)
                    return false;
            });
        });
    };
})(jQuery);

And to use it

 $(input).numeric({ max: 999,maxLength:4});

maxLength - property indicates maximum input length

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23132

It can be cumbersome to validate on every keypress event, and just returning false from a keypress doesn't let the user know why they're not allowed to input that key. You probably have the field marked as numeric in the label or something like that, but any extra help you can give to the user, even if the user is just yourself, can save a lot of annoyance down the road. What about something like this?

(function($) {
    $.fn.numeric = function(options) {
        return this.each(function () {
            var $this = $(this);

            $this.blur(function(e) {
                if (isNaN(+this.value)) {
                    $('<span class="error">Must be numeric</span>').insertAfter($this);
                } else {
                    $this.next('span.error').remove();
                }
            });
        });
    };
}(jQuery));

There's a working example here.

Also, you'll need to add back your min/max check from the options. I removed that for this example's sake.

Finally, if you are going to be doing a lot of validation, you might want to use a validation library like jQuery Validation, instead of rolling your own.

Upvotes: 0

Guillaume Cisco
Guillaume Cisco

Reputation: 2945

This code should work as you expected :

(function($) {
    $.fn.numeric = function(options) {
        return this.each(function() {
            var $this = $(this);

            $this.keypress(options, function(e) {
                // allow backspace and delete
                if (e.which == 8 || e.which == 0) {
                    return true;
                }

                // allow float
                if (e.which == 46 && this.value.length >=1 && this.value.indexOf('.') == -1) {
                    return true;
                }

                //if the letter is not digit
                if (e.which < 48 || e.which > 57) return false;

                // check max range
                var dest = e.which - 48;
                var result = this.value + dest.toString();
                if (result > e.data.max) {
                    return false;
                }
            });
        });
    };
})(jQuery);

demo : http://jsfiddle.net/GuillaumeCisco/nGNxG/

Upvotes: 1

Umesh Patil
Umesh Patil

Reputation: 10685

I tried debugging the code. You should require only update for '.'. ASCII value of '.' (dot) is 46. If you do below changes it will work !

  1. Update (e.which == 8 || e.which == 0) with (e.which == 8 || e.which == 0||e.which==46)
  2. You require to wrap input with quotes - $('input').numeric({ max: 999});
  3. Test by alerting the value with the code alert(parseInt($('input').val()));

I saw above changes solves this problem :) Please, Let me know if it doesn't work :)

Upvotes: 0

Andr&#225;s V&#225;czi
Andr&#225;s V&#225;czi

Reputation: 3002

Check this answer and the comments (especially the accepted one): Validate decimal numbers in JavaScript - IsNumeric()

Otherwise, is it really necessary to check your value on every keypress?

Upvotes: 1

Related Questions