Click to See Complete Forum and Search --> : regular expresssion pattern help (simple)


msimon7
09-21-2004, 12:57 PM
hello.
i have a need to validate a users input of a numeric percentage field.
the field can contain a value anywhere from 0 to 100 and 2 decimal places are allowed. i would like to try to do this with regular expression pattern, but all patterns i've tried so far have not worked.:mad:
so entering something like 4 or 34.23 or 100 is acceptable, but something like 3.123 or 101 or 100.1 or 100.01 is not.
so what would the correct pattern be?
tried \[0-100.00]\ and a lot of others, no luck so far...

hopefully this is simple question for you out there.
do appreciate the help!
thanks

Jona
09-21-2004, 01:00 PM
<script type="text/javascript"><!--
/* Untested, but should work. */
var re = /\d+\.\d{2}/i;
var floatie = 128.32234242;
alert(re.exec(floatie));
//--></script>

msimon7
09-21-2004, 01:26 PM
hello. thank you for the reply.
i searched this site (did this also before i posted my question as well) and just found a very nice site that has a library of expressions
http://regexlib.com/Default.aspx
thru there i found one that works and figured i should share it incase anyone has the same question as i did...

^(100(?:\.0{1,2})?|0*?\.\d{1,2}|\d{1,2}(?:\.\d{1,2})?)$

Author: Darren Neimke
Sample Matches: 0|||100|||.17%
Sample Non-Matches: 101|||-17|||99.006
Description: Matches a percentage between 0 and 100 (inclusive). Accepts up to 2 decimal places.

man, my first attempt at a pattern kinda looks pretty stupid compared to final result that actually does what i want :D

Jona
09-21-2004, 01:30 PM
Well, glad you got it solved. My original code (which I just tested) does indeed work, but any empty values are converted to zeros -- instead of requiring that the certain format was met which it can easily be modified to do. It also doesn't require as much processing as the RegEx you found. Edit: The only difference is that mine does not take into consideration if the value is less than zero or greater than one hundred.


<script type="text/javascript"><!--
var re = /^\d+\.\d{2}$/;
var floatie = 128.32;
// use the following to get an "invalid" message
// var floatie = 128.28309;
if(re.test(floatie)){
alert(floatie + " is valid.");
} else {
alert(floatie + " is invalid.");
}
//--></script>

msimon7
09-21-2004, 01:32 PM
i apprecite the reply and will save your sample, as i'm sure it will come in handy in the future. thanks again for the sample and info!

Jona
09-21-2004, 01:33 PM
Happy to help.