Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(How-to) JavaScript - Test for Unsigned Integer (UINT) using Regular Expressions (RegExp)

Problem: How to test/check if a value is an Unsigned Integer (UINT) in JavaScript.

Alternative Answers: Thanks goes to the following for improving this answer!

@jbabey:if Number(val) > 0

@SLaks:if (/^\d+$/.test(someString))


About: This shows how to test/check if a value is an Unsigned Integer (UINT) in JavaScript.


Usage: JS: isUINT( value );


Returns: True OR False


Expanded Version:

<script type="text/javascript">
    function isUINT(v)
    {
        var r = RegExp(/(^[^\-]{0,1})?(^[\d]*)$/);
        return r.test(v) && v.length > 0;
    }
</script>

Minified Version:

function isUINT(v){var r=RegExp(/(^[^\-]{0,1})?(^[\d]*)$/);return r.test(v)&&v.length>0}

Comments / Alternatives are Welcomed!

like image 752
Trenton Bost Avatar asked Jun 25 '26 03:06

Trenton Bost


2 Answers

if (/^\d+$/.test(someString))

like image 199
SLaks Avatar answered Jun 26 '26 17:06

SLaks


Old question but now you can use

const isUINT = (val) => Number.isInteger(val) && val >= 0

console.log('"a":', isUINT('a'))
console.log('"1":', isUINT('1'))
console.log('null:', isUINT(null))
console.log('-1:', isUINT(-1))
console.log('0:', isUINT(0))
console.log('1:', isUINT(1))
console.log('1.25:', isUINT(1.25))
console.log('0.25:', isUINT(0.25))
like image 32
jkutianski Avatar answered Jun 26 '26 17:06

jkutianski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!