Angular 6 validate number input

anhtv13 picture anhtv13 · Oct 24, 2018 · Viewed 66.2k times · Source

I have an input and the type is number. I want to set min and max, if the input is out of this range (< min or >max), the error will be displayed.

My problem is that if the input is not empty but invalid, the error disappears (example: min =10, max =20, input =2000, still no error displays).

I search on this site and there is a post about validation but the solution is to use < md-input-container> and < md-error>. I don't want to use < md-input-container> and < md-error>.

Reference:here

Is there anyway to solve my problem?

My add-hero.component.html:

<div class="publishedYear">
<label>Publish Year: </label>
<input type="number" id="PublishedYear" name="PublishedYear" required min="10" max="20" 
[(ngModel)]="hero.PublishedYear" #publishedYear="ngModel">
<p class="alert alert-danger invalid" *ngIf="publishedYear.errors">Invalid Published Year</p>
</div>

My Hero.ts

export class Hero {
Id: number;
Name: string;
PublishedYear: number;
Complete?: boolean;
}

Answer

Hrishikesh Kale picture Hrishikesh Kale · Oct 24, 2018

To your solutions when you are using input type="number" setting min and max will only stop allowing user when he will increment or decrement number using the scroller. but when user will type the number directly in the text it won't show any error

to do that there are 2 solutions

1) Add form control to your input using angular form validation there will be a couple of examples online

2) Call a function on on-change of a text box or on button click to validate the number entered by a user matches your expression in ts file.

using form validation you need to do

myForm = new FormGroup({}) // Instantiating our form

constructor(private fb: FormBuilder){ // Injecting the ReactiveForms FormBuilder.
  this.myForm = fb.group({
    // Adding the "myNum" input to our FormGroup along with its min-max Validators.
    'myNum': ['', [Validators.min(5), Validators.max(10)]] 
  })
}

and in HTML

<form [formGroup]="myForm"> <!-- Binding myForm to the form in the template -->
    <label for="myNum">Some Val</label>
    <!-- formControlName binds our myNum field declared in the ts code. -->
    <input type='number' id="myNum" formControlName="myNum">
    <div *ngIf="myForm.controls['myNum'].hasError('max')">
          Minimum required number is 15.
    </div> 
</form>