pooh098
pooh098

Reputation: 191

Angular2 setting min and max value of input field

I'm new to Angular2. I'm trying to restrict user input to numbers between 110 and 5000. I don't want to do just user input validation. I will like to prevent a user from putting different values than numbers between 110 and 5000. I tried to do it max and min but it only works for up and down key strokes.

Here is HTML part:

<div class="form-group">
    <label for="flowRate">Flow Rate</label><br>
    <div class="input-group calc-addon-group">
      <input class="form-control addon-input" type="number" step="any" [(ngModel)]="tmpFlowRate" id="flowRate" onfocus="this.select();">
      <span class="input-group-addon units">{{settings.flowMeasurement}}</span>
    </div>
  </div>

Upvotes: 2

Views: 2101

Answers (2)

Garth Mason
Garth Mason

Reputation: 8001

In the latest Angular version, it appears that validators were added for min and max range but that it has been rolled back - see issue here.

In the meantime you are probably best off using either a regex (pattern) validator, or writing your own custom validator directive to enforce the valid range of values.

See the official doco or the examples by Thoughtram for info on custom validators.

Upvotes: 1

ebraley
ebraley

Reputation: 206

I've found that input validation is a nightmare in Angular 2, there's no easy straightforward way. If you're going to be doing a lot of input validation and such, I'd recommend transitioning to utilizing Model Driven/Reactive Forms.This resource is a great starting point for what you need.

I'd also recommend transitioning to Angular4. A lot of bug-fixes for Angular2 just went straight into Angular4 and most libraries are moving on to Angular4 from Angular2. Your Angular2 code shouldn't need to be modified substantially to make the transition.

Upvotes: 1

Related Questions