0

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?

Naeem Ul Wahhab
  • 2,465
  • 4
  • 32
  • 59
monir tuhin
  • 441
  • 3
  • 13
  • 27

3 Answers3

3

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".

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • thanks Wiktor Stribiżew. your code does not work properly for me. but i have found a solution. this is : ng-pattern="/^\d\.\d{0,2}$/" – monir tuhin Jul 31 '17 at 11:38
  • @monirtuhin That won't allow valid float numbers like `.123`. Also, that won't match `12.4`. And that will match `1.` (no idea if that is important here). – Wiktor Stribiżew Jul 31 '17 at 11:39
  • I wanted one digit befor dot(.) and two digit after dot(.) like (2.50) . in this way this solution helped me. thanks wiktor – monir tuhin Jul 31 '17 at 11:44
  • @monirtuhin There are no exact requirements in the question, so my answer is valid. Yours is too restricted. If my answer helped, feel free to upvote it. – Wiktor Stribiżew Jul 31 '17 at 11:50
  • 1
    your answer also helped me to identify my problem. thanks – monir tuhin Jul 31 '17 at 11:53
0

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.

0

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

ng-pattern="/^\d\.\d{0,2}$/"
monir tuhin
  • 441
  • 3
  • 13
  • 27
  • `/^\d\.\d{0,2}$/` won't allow valid float numbers like `.123`. Also, that won't match `12.4`. And that will match `1.` (no idea if that is important here). – Wiktor Stribiżew Jul 31 '17 at 11:40
  • @ Wiktor Stribiżew I wanted one digit befor dot(.) and two digit after dot(.) like (2.50) . in this way this solution helped me. thanks – monir tuhin Jul 31 '17 at 11:51