Possible Duplicate:
Javascript percentage validation
I want to allow 0.00 to 100.00 only.
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.replace(/[^\d.d]+/g, '');
}
}
<asp:textbox id="txtrate" runat="server" Width="200px" onkeyup= "javascript:ValidateText(this)"></asp:textbox>
It allows 0-9.0-9. Help me please. Thanks
Now this is some popular question!
This should do:
function validate(s) {
return s.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
}
var test = [
'3.0',
'5',
'99.99',
'100',
'100.00',
'100.01',
'101',
'0.3',
'.5',
'0.567',
];
for (i=0; i<test.length; ++i) {
WScript.StdOut.WriteLine(test[i] + ' => ' + validate(test[i]));
}
Outputs:
3.0 => true
5 => true
99.99 => true
100 => true
100.00 => true
100.01 => false
101 => false
0.3 => true
.5 => false
0.567 => false
Edit: the regexp can be shortened a bit without changing its meaning, credits to 6502
/^(100(\.00?)?|[1-9]?\d(\.\d\d?)?)$/
This expression should allow only what you are asking for
/^[1-9]?\d(\.\d\d?)?|100(\.00?)?)$/
Meaning is
^ start of string
( start of sub-expression ("or" between two possibilities)
[1-9]? an optional non-zero digit
\d followed by a digit
(\.\d\d?)? optionally followed with a dot and one or two digits
| or
100 the string "100"
(\.00?)? optionally followed by a dot and one or two zeros
) end of sub-expression
$ end of string
Try this one
^(?:\d{1,2}(?:\.\d{1,2})?|100(?:\.0?0)?)$
See it here on Regexr
(?:)
are non capturing groups, that means the match from this group is not stored in to a variable.
\d{1,2}
matches 1 or 2 digits
(?:\.\d{1,2})?
This is optional, a .
followed by 1 or two digits
or
100(?:\.0?0)?)
matches 100
optionally followed by 1 or 2 0
^
matches the start of the string
$
matches the end of the string
Those two anchors are needed, otherwise it will also match if there is stuff before or after a valid number.
Update: I don't know, but if you want to disallow leading zeros and numbers without two digits in the fraction part, then try this:
^(?!0\d)(?:\d{1,2}(?:\.\d{2})|100\.00)$
I removed the optional parts, so it needs to have a dot and two digits after it.
(?!0\d)
is a negative lookahead that ensures that the number does not start with a 0 and directly a digit following.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With