Abhishek Saha
Abhishek Saha

Reputation: 25

Restrict input to the range 1..25 with Angular

In an input form like the following:

<div class="row">
  <label for="input">Value</label>
  <input type="text" id="input" [(ngModel)]="player.input" name="input" 
  required pattern="   ([1-9]+(\.[0-9]{1,2})?|[1][0-9]+(\.[0-9]{1,2})|[2][0-4]+(\.[0-9]{1,2})?|25|25.0|25.00)" #input="ngModel">
  <div [hidden]="input.valid || input.pristine"
  class="alert alert-danger">
  input must be between 1-25 with decimal places
</div>
</div>

How can I restrict the input to the range of 1 to 25, inclusive, with two decimal places?

Valid inputs: 25.00, 24.99, 08.89, 9.98

Invalid inputs: 255.00, 244.999, 24.999

Upvotes: 1

Views: 57

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Try this regex:

^(([1-9]|1[0-9]|2[0-4])(\.[0-9]{1,2})?|25|25\.0|25\.00)$

Explanation:

(
    [1-9]        match 1-9
    1[0-9]       match 10-19
    2[0-4]       match 20-24
)
(\.[0-9]{1,2})?  match an optional decimal component with 1 or 2 digits
|25|25\.0|25\.00 or match 25, 25.0, or 25.00 exactly

Demo

Upvotes: 2

Related Questions