Click here to Skip to main content
15,122,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm having a page with text boxes (with maxlength 2)which should take only numbers from 1-25. Anything except numbers like spaces, characters, -ve values or alphabets etc, i've written code to change the textbox background to yellow as below

JavaScript
$("#divBingoKeyIn input:text").each(function () {
                   var currentValue = $(this).attr("value");
                   if (currentValue == "" || parseInt(currentValue) > 25 || parseInt(currentValue) < 1) {
                       $(this).css("background-color", "yellow");
                       isValuesValid = false;
                   }
                   else {
                       $(this).css("background-color", "White");
                   }


But for above code i've used primitive methods to find if it is not a number.

i would like to replace this with a simple code like below

JavaScript
$("#divBingoKeyIn input:text").each(function () {
                    var currentValue = $(this).attr("value");
                    if (currentValue.match(regex)) {
                        $(this).css("background-color", "yellow");
                        isValuesValid = false;
                    }
                    else {
                        $(this).css("background-color", "White");
                    }


Can anybody please give me a regex for the above scenario?
Posted

1 solution

Regex is not a good solution - it is a text matching system, not a number matching.
It could be done with a regex, but it would be realy silly: it would have to include all the cases that are allowed, each spelt out:
^(1|2|3|4|5|6|7|8|9|10|11|...|23|24|25)$
Which is plain stupid. You are better off handling this kind of thing in code!
   
Comments
DieOnTime 26-Feb-12 3:07am
   
if possible can you please suggest other alternate ways to restrict anything but numbers?
OriginalGriff 26-Feb-12 3:29am
   
Numbers is easy as a regex: ^(\d|\d\d)$ will restrict it to a digit or two digits.
DieOnTime 26-Feb-12 4:14am
   
My string.match is returning null for 2 as per the above regex.

alert(txtValue.match("^(\d|\d\d)"));

Can you please advise if there is anything which needs to be added or modified??
OriginalGriff 26-Feb-12 4:27am
   
First off you need the '$' on the end, or "299999" will match "2" and stop.

Really - do it in code, it is a lot more reliable with a problem like this. Forget regex for number matching - code will be quicker, more readable, and more maintainable.
DieOnTime 26-Feb-12 3:08am
   
Also forgot to mention, it's just plain html and jQuery i'm using.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900