How to create a regular expression for cricket overs

362 views Asked by At

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

2

There are 2 answers

3
Gabi Purcaru On BEST ANSWER

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.

2
Chandu On

Try this:

<script type="text/javascript">
var testString = '5.4';
var regExp = /^\d+(\.[1-5])?$/;
if(regExp.test(testString))
{
 // Do Something
}
</script>