Praveen M P Praveen M P - 9 months ago 49
Javascript Question

How to show error message when the user enters only 0 or 0.0 using regular expression in angular

I have a specific requirement for the input field.

  • It should not allow 0 and show error message saying value should be greater than 0.

  • It should not allow any string characters.

  • it should work for 0.123, 0.1, 1.0

    Would it be possible using regular expression or do I need to write a JavaScript function to validate these conditions

This is what i have tried


Fiddler Link here

Answer Source

You may restrict the input by adding a negative lookahead into the regex:


The (?!0+(?:\.0+)?$) negative lookahead fails the match (and will cause the error message to appear) once the user types zero(s) optionally followed with . + zero(s) only.

More details:

  • ^ - start of string
  • (?!0+(?:\.0+)?$) - there must be no one or more zeros optionally followed with . + one or more zeros
  • [0-9]+ - 1+ digits
  • ([.][0-9]+)? - an optional sequence of . + 1+ digits
  • $ - end of string.

Link to updated fiddle