0

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!!

3
  • 2
    return /\d{4}/.test(b) Commented Feb 14, 2014 at 11:48
  • @pawel Why isNumeric("+1234") is true?? Commented Feb 14, 2014 at 11:52
  • 1
    because it passes the above test, sorry ;) use /^\d{4}$/.test(b) instead. Commented Feb 14, 2014 at 11:53

4 Answers 4

2

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})$/
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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');
});

Comments

1

you can check it like:

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

}

and using regex you can do:

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

1 Comment

parseInt("+123") == 123

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.