I have this code:

isTinyInt: function () {
        var val = $(this).val();
        if (val >= 0 && val <= 255)
            return true;
        else
            return false;
    }



Can I make sure with this that the number is in the tinyint range?

Recommended Answers

All 3 Replies

signed or unsigned tinyint?

unsigned tinyint

Your function looks good though it will only work if this is an appropriate DOM elememt.

You might like to consider a generalised int verifier framed as a jQuery plugin :

jQuery.fn.isInSqlIntRange = function (options) {
    var settings = $.extend({
        'type': 'int',
        'unsigned': false
    }, options);
    var min, max, val = this.val();
    if (val === '' || Number(val) === NaN) {
        return false;
    }
    val = Number(val);
    switch (settings.type) {
        case 'tinyint':
            min = settings.unsigned ? 0 : -128;
            max = settings.unsigned ? 255 : 127;
            break;
        case 'smallint':
            min = settings.unsigned ? 0 : -32768;
            max = settings.unsigned ? 65535 : 32767;
            break;
        case 'mediumint':
            min = settings.unsigned ? 0 : -8388608;
            max = settings.unsigned ? 16777215 : 8388607;
            break;
        case 'int':
        case 'integer':
            min = settings.unsigned ? 0 : -2147483648;
            max = settings.unsigned ? 4294967295 : 2147483647;
            break;
        case 'bigint':
            min = settings.unsigned ? 0 : -9223372036854775808;
            max = settings.unsigned ? 18446744073709551615 : 9223372036854775807;
            break;
        default:
            throw typeError('jQuery.isInIntRange() - type is undefined or invalid');
    }
    return val >= min && val <= max;
}

Sample call :

var foo = $("#myInput").isInSqlIntRange({
    'type': 'tinyint',
    'unsigned': true
});

DEMO

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.