niccoicco9
niccoicco9

Reputation: 73

How can I limit the input number range with angular

I would like to limit the input number that can go up to the current year, the user cannot enter a year higher than the current one. How can I do it?

My code:

<ion-content >
 <form>
  <ion-list>
    <ion-item>
      <ion-label>Stagione</ion-label>
      <ion-input [(ngModel)]="season.Description"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Year</ion-label>
      <ion-input [(ngModel)]="season.Year" type="number"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Primavera/Estate</ion-label>
      <ion-checkbox [(ngModel)]="season.IsSpringSummer"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Default</ion-label>
      <ion-checkbox [(ngModel)]="season.IsDefault"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Nascosto</ion-label>
      <ion-checkbox [(ngModel)]="season.IsHidden"></ion-checkbox>
    </ion-item>

  </ion-list> 

</ion-content>
<ion-footer>
  <ion-toolbar color="footer">
    <ion-buttons right>
  <button ion-button clear color="dark" (click)="save()">Save&nbsp;

      </button>

    </ion-buttons>
  </ion-toolbar>

</ion-footer>

Upvotes: 1

Views: 12717

Answers (3)

AlessioF
AlessioF

Reputation: 453

I suggest you simply to do a check in function save(). It can be like this:

if((new Date()).getFullYear() < this.season.Year) {
   //display an error message, maybe using alert or toast
}

Upvotes: 2

vishulg
vishulg

Reputation: 149

You can do it simply by HTML only:

<input type="number" oninput="if(value > (new Date()).getFullYear()) alert('Year exceeds current year')">

If you really want to do it by Angular only you have to create custom Validator which you can find in the link given below:

Min / Max Validator in Angular 2 Final

If you are using Angular 6 then you can use min and max validators which you can find in the link given below:

https://angular.io/api/forms/Validators#min

Upvotes: 2

Sourangshu Sengupta
Sourangshu Sengupta

Reputation: 156

You can make use of the min and max properties.

Bind the max property to the current year like so: <ion-input [(ngModel)]="season.Year" type="number" [max]="{{(new Date()).getFullYear()}}"></ion-input>.

The logic for getting the full year could be moved to the typescript file and could be stored in a variable like currentYear. In the template we can then bind to max like so: [max]="currentYear".

Upvotes: 3

Related Questions