Question

Please tell me what regular expression should i use to validate cricket overs in textbox. like it can be 5.1, 5.2,5.3,5.4,5.5 but it should not contain fraction value greater than .5 ,also the values should be numeric only (float and int)

Thanks

Was it helpful?

Solution

You should use this:

^[0-9]+(\.(50*|[0-4][0-9]*))?$

If you also want fractions like .2 instead of 0.2, use this:

^[0-9]*(\.(50*|[0-4][0-9]*))?$

Explained:

^                beginning of the string
[0-9]*           repeat 0 or more digits
(
  \.             match the fraction point
  (
     50*         match .5, or .5000000 (any number of zeros)
     |           or 
     [0-4][0-9]* anything smaller  than .5
  )
)?               anything in this parenthesis is optional, for integer numbers
$                end of the string

Your version, [0-9]+(\.[0-5])? does not work unfortunately, because, for example /[0-9]+(\.[0-5])?/.test("0.8") yields true.

OTHER TIPS

Try this:

<script type="text/javascript">
var testString = '5.4';
var regExp = /^\d+(\.[1-5])?$/;
if(regExp.test(testString))
{
 // Do Something
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top