简体   繁体   中英

angular 2 formbuilder min max validation

I am using angular 2 formbuilder to create a form. I want to input only positive values to the amount field.(minValue is 0 and maxvalue is 100) How can I perform min and max validation with angular2 formbuilder.

Html code

 <form class="form-horizontal"
              novalidate
              (ngSubmit)="splitCharges()"
              [formGroup]="splitChargeForm" >
    <input  type="number" id="sequenceId"  placeholder="Amount" formControlName="amount"  >
 </form>

angular component

 constructor(private fb: FormBuilder){}

 ngOnInit() {
        this.splitChargeForm = this.fb.group({
          amount: ['', Validators.required],   // want to set min=0 and max=100 validations for this field
          percentage: ['', Validators.required]
        });
    }

This should do what you want:

amount: ['', [Validators.required, Validators.min(0), Validators.max(100)]],

See also https://angular.io/guide/form-validation#component-class-1

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