super cool
super cool

Reputation: 6045

Regex expression is not working?

I am trying to build a regex expression with this requirement .

Requirement :

Max length - 5(inc decimal dot if is a decimal number)

Decimal precession - max 2 digits (if it is a decimal numer ).

Number - need not to be a decimal number (not mandatory)

Code:

<script>
function myFunction() {
   var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
    var num = 12345.52; // i will test here indiffernt ways
    var n = regexp.test(num)
    document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>

Output should look like :

12345.52 -->It should return false as length is 8 inc dot but it returns true

123456.52 --> false . I came to know d{0,5} is looking for before decimal

12.45 --> true . Perfect one (length 5 , precession 2 )

12345 --> true . Perfect one (length 5 , precession- not madatory)

I am hoping to build a regex expression satisfies all the above scenarios .

Reference : Click Here

Upvotes: 4

Views: 97

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below regex which uses positive lookahead assertion.

^(?=.{1,5}$)\d+(?:\.\d{1,2})?$

DEMO

Explanation:

  • ^ Asserts that we are at the start.
  • (?=.{1,5}$) Asserts that the length must be from 1 upto 5.
  • \d+ Allows one or more digits.
  • (?:\.\d{1,2})? Optional decimal part with the allowable digits after the decimal point must be one or two.
  • $ Asserts that we are at the end of the line.

Upvotes: 6

Related Questions