Forum Moderators: open

Message Too Old, No Replies

Regular Expression

Required Regular Expression for Percentage value validation

         

JavaGuy

11:24 am on Dec 8, 2006 (gmt 0)

10+ Year Member



Hi,
I am new to this forum and regular expression. I need to validate a textfield where I need to allow only numeric values and below 100.
User may enter like 7.5 or 35.50, 34.6, etc. And I need to restrict two digits of decimal values not more than that. eg. 35.56. It should not allow like 34.3456.
Can you anyone help me?

coopster

4:45 pm on Dec 8, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Hi JavaGuy, welcome to WebmasterWorld.

One possible solution might be something like ...

function lessThanOneHundred(element) 
{
var re = /^\d{0,2}(\.\d{0,2})?$/
if (element.value &&!re.test(element.value)) {
alert('The value must be < 100 with only 2 decimal places.')
element.focus()
element.select()
return false
}
return true
}

Fotiman

5:15 pm on Dec 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm no RegExp expert, but here's what I would think:

// Match 0-3 digits: \d{0,3}
// at the start of the string: ^\d{0,3}
// followed by:
// a decimal followed by 0-2 characters at the end of the string: \.\d{0,2}$
// OR
// the end of the string: $
var reg = /^\d{0,3}(\.\d{0,2}$¦$)/;
var val = "100.00";
var result = reg.test(val);
alert(result);

However, this only checks the number of digits. You'll still need to check the value separately to see if it's greater than 100.00.