How to allow only 3 digit and one dot in Regular Expression

2.6k Views Asked by At

I want to do like this : 3.40 and not more than 3 characters and one dot:

<md-input-container class="md-block">
                    <label>Marks/CGPA</label>
                    <input type="text" name="education.cgpa" ng-model="education.cgpa"
                           ng-pattern="/^[0-9]{0,4}$/">
                    <div class="input-validation" ng-show="educationSaveForValidate['education.cgpa'].$error.pattern">
                        Insert valid CGPA
                    </div>
                </md-input-container>

How can I allow only 3 digits and one dot in Regular Expression?

3

There are 3 best solutions below

2
On

i have solved my problem this way......

ng-pattern="/^\d\.\d{0,2}$/"
5
On

You may use a single regex like

ng-pattern="/^(?!.{5})\d*\.?\d+$/"

or - to allow an empty string:

ng-pattern="/^(?!.{5})\d*\.?\d*$/"

You may also move the length check out of the regex:

ng-pattern="/^\d*\.\d*$/" ng-maxlength="4"

Details

  • ^ - start of string
  • (?!.{5}) - a negative lookahead that fails the match if there are any 5 chars in the input string
  • \d* - 0+ digits
  • \.? - an optional .
  • \d* - zero or more digits (if \d+ is used, then 1 or more digits)
  • $ - end of string.

To disallow any leading/trailing spaces, add ng-trim="false".

0
On

https://regex101.com/r/kF0hJ5/17

Check this link above, I hope it'll help you. Sorry for commenting link here. Doing so as I have less repo.