简体   繁体   中英

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>

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" .

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM