[jquery] Validate that text field is numeric usiung jQuery

I have a simple issue -- I would like to check a field to see if it's an integer if it is not blank. I'm not using any additional plugins, just jQuery. My code is as follows:

if($('#Field').val() != "")
{
    if($('#Field').val().match('^(0|[1-9][0-9]*)$'))
    {
        errors+= "Field must be numeric.<br/>";
        success = false;
    }
}

...It doesn't seem to work. Where am I going wrong?

The error I receive is val() is not an object.


It turned out that the real issue was that I had my element name set and not the Id.

This question is related to jquery validation

The answer is


I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/

if($('#Field').val() != "")
{
    if($.isNumeric($('#Field').val()) {
        errors+= "Field must be numeric.<br/>";
        success = false;
    }
}

You don't need a regex for this one. Use the isNAN() JavaScript function.

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.

if (isNaN($('#Field').val()) == false) {

    // It's a number
}

All basic validation by using a class:

$('.IsInteger,.IsDecimal').focus(function (e) {
    if (this.value == "0") {
        this.value = "";
    }
});
$('.IsInteger,.IsDecimal').blur(function (e) {
    if (this.value == "") {
        this.value = "0";
    }
});

$('.IsInteger').keypress(function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (charCode > 31
    && (charCode < 48 || charCode > 57))
        return false;
});
$('.IsDecimal').keypress(function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (this.value.indexOf(".") > 0) {
        if (charCode == 46) {
            return false;
        }
    }
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
});
$('.IsSpecialChar').keypress(function (e) {
    if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
        return false;
    else
        return true;
});
$('.IsMaxLength').keypress(function (e) {
    var length = $(this).attr("maxlength");
    return (this.value.length <= length);
});

$('.IsPhoneNumber').keyup(function (e) {
    var numbers = this.value.replace(/\D/g, ''),
    char = { 0: '(', 3: ') ', 6: ' - ' };
    this.value = '';
    for (var i = 0; i < numbers.length; i++) {
        this.value += (char[i] || '') + numbers[i];
    }
});
$('.IsEmail').blur(function (e) {
    var flag = false;
    var email = this.value;
    if (email.length > 0) {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        flag = regex.test(email);
    }
    if (!flag)
        this.value = "";
});

Example:

<asp:TextBox 
    runat="server" 
    ID="txtDeliveryFee" 
    TextMode="SingleLine" 
    CssClass="form-control IsInteger" 
    MaxLength="3" 
    Text="0"
></asp:TextBox>

Just put the class name in the input.


I know there isn't any need to add a plugin for this.

But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.

The rest of karim79's answer is super cool.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.numeric.js"></script>
    </head>

    <body>
        <form>
            Numbers only:
            <input class="numeric" type="text" />
            Integers only:
            <input class="integer" type="text" />
            No negative values:
            <input class="positive" type="text" />
            No negative values (integer only):
            <input class="positive-integer" type="text" />
            <a href="#" id="remove">Remove numeric</a>
        </form>

        <script type="text/javascript">
            $(".numeric").numeric();

            $(".integer").numeric(false, function() {
                alert("Integers only");
                this.value = "";
                this.focus();
            });

            $(".positive").numeric({ negative: false },
                function() {
                    alert("No negative values");
                    this.value = "";
                    this.focus();
                });

            $(".positive-integer").numeric({ decimal: false, negative: false },
                function() {
                    alert("Positive integers only");
                    this.value = "";
                    this.focus();
                });

            $("#remove").click(
                function(e)
                {
                    e.preventDefault();
                    $(".numeric,.integer,.positive").removeNumeric();
                }
            );
        </script>

    </body>
</html>

Regex isn't needed, nor is plugins

if (isNaN($('#Field').val() / 1) == false) {
    your code here
}