2

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>
1
  • Consider using Angular 2 Formly it is superior to the official @angular/forms which offers two uniquely bad and incompatible APIs. Commented Jul 20, 2017 at 2:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is useful resource but just for basic user validation and user message.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.