Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regular expression for percentage between 0 and 100 [duplicate]

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

like image 335
z0mbie Avatar asked Jul 06 '11 07:07

z0mbie


3 Answers

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?)?)$/
like image 107
SnakE Avatar answered Oct 04 '22 01:10

SnakE


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
like image 40
6502 Avatar answered Oct 04 '22 00:10

6502


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.

like image 43
stema Avatar answered Oct 04 '22 02:10

stema