Ansuman
Ansuman

Reputation: 1494

Checking for Integers in javascript

I have a regular expression where I'm checking if a text entry is numeric. This is Year field and it should accept only integers like 1999 or 2000 etc. But in this case it's also accepting -, +, . etc.

isNumeric = function(b){
    return(b-0) == b&&(b+"").replace(/^\s+|\s+$/g,"").length > 0
};

Could you please help me out!!

Upvotes: 0

Views: 93

Answers (4)

Mehran Hatami
Mehran Hatami

Reputation: 12961

you can check it like:

if(!isNaN(parseInt(yourstring))){

}

and using regex you can do:

/^[0-9]+$/i.test(yourstring)

Upvotes: 1

Nicholas Murray
Nicholas Murray

Reputation: 13533

If you wish to validate a range of (positive) years for example 1980 to 2020 where the string '+2000' is not accepted.

isNumeric = function(b){
    return /^(198\d|200\d|2020)$/.test(b);
}

This will pass the following tests - it's tested here

Function renamed to yearRange

yearRange = function(b){
    return /^(198\d|200\d|2020)$/.test(b);
}


test('Year range validation', function() {
   equal( yearRange(1979), false, '1979 returns false');
   equal( yearRange(1980), true, '1980 returns true');
   equal( yearRange('2000'), true, 'The string 2000 returns true');
   equal( yearRange(+2000), true, '+2000 returns true' );
   equal( yearRange(-2000), false, '-2000 returns false' );
   equal( yearRange('+2000'), false, 'The string +2000 returns false');
   equal( yearRange('-2000'), false, 'The string -2000 returns false');
});

Upvotes: 1

NiiL
NiiL

Reputation: 2827

better solution is to restrict user to enter key other than Numeric using Javascript Create function like this:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

and add onkeypress Event to your Textbox:

<input type="text" class="textfield" value="" id="extra7" name="extra7"
onkeypress="return isNumber(event)" />

Demo: JS Fiddle

You can also restrict user to enter only 4 Numerics by adding maxlength="4" to inbox.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

If you need to accept years of 20th and 21th centuries, a more refined regexp could be

isNumeric = function(b){
    return /^(19|20)\d{2}$/.test(b)
};

if you need to accept always a 4-digit year, the regular expression is simply

/^\d{4}$/

and if you need to accept every year from 0 to 9999 (where a trailing 0 is not accepted)

/^(0|[1-9]\d{0,3})$/

Upvotes: 2

Related Questions