Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking only integer digit using RegEx in JQUERY

Tags:

jquery

regex

I have following code snippet:

    var reg = /^[0-9]$/;

    $('input[type="text"]').keypress(function(){
       console.log(reg.test(parseInt($(this).val())));
    });

When I press any key (digit or other) it always return false. But I can't find out the problem.Please give me some solutions.

like image 712
thecodeparadox Avatar asked May 22 '26 08:05

thecodeparadox


2 Answers

See How to allow only numeric (0-9) in HTML inputbox using jQuery? for a proper solution.

In case you want to do something own, have a look at those plugins anyway. It's very important to not break common things like backspace (or ctrl+c/v/x) as users usually expect those keys to work.

like image 100
ThiefMaster Avatar answered May 24 '26 21:05

ThiefMaster


The regex you've created tests for exactly 1 occurance of any digit. It also asserts that it's the begining of the string followed by a single digit, then the end of string.

The keypress event is triggered before actual content is put into the textbox. This should only work for the second key press, because that's when the textbox content .val() yields exactly 1 digit.

If you follow the link posted by @ThiefMaster you'll find the answer to your question. You'll also note that it's using the charCode and keyCode properties of the event object to do validation not the contents of the textbox.

like image 26
John Leidegren Avatar answered May 24 '26 22:05

John Leidegren