角度输入最小值验证

时间:2018-08-16 11:10:14

标签: angular angular-material

即使我可以成功验证required,我也无法验证材料输入中的最小数量。

<input min="0.01" matInput type="number" placeholder="Amount" style="width: 49%;" [formControl]="numberControl" name="amount"
            [(ngModel)]="amount" required>
  <mat-hint>
     <strong>Available cash: {{selectedMovementFrom?.portfolioValue | currency: 'GBP': 'symbol'}}</strong>
  </mat-hint>

  <mat-error *ngIf="numberControl.hasError('min')">
    Amount cannot be negative.
  </mat-error>

  <mat-error *ngIf="numberControl.hasError('required')">
    Please enter amount.
  </mat-error>

我还尝试通过引用errors对象来检查验证,如下所示:

<mat-error *ngIf="numberControl.errors?.min">
   Amount must be greater than £0.00
</mat-error>

但是,在检查了我仍然不明智的文档之后,这也不会显示错误。

我错过了任何指针或明显的东西吗?

2 个答案:

答案 0 :(得分:0)

import { Directive } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator, FormControl } from '@angular/forms';
@Directive({
  selector: '[appMinAmountValidator] [ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: MinAmoutValdiatorDirective, multi: true }
  ]
})
export class MinAmoutValdiatorDirective implements Validator{

  validator: ValidatorFn;
  constructor() {
    this.validator = validateminAmount();
  }
  validate(c: FormControl) {
    return this.validator(c);
  }

}



// validation function
function validateminAmount() : ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = c.value >0;

    if(isValid) {
      return null;
    } else {
      return {
        isminAmountValid: {
          valid: false
        }
      };
    }

  }
}

答案 1 :(得分:0)

像这样给它

 <input [min]="0.01" matInput type="number" placeholder="Amount" 
 style="width: 49%;" [formControl]="numberControl" name="amount"
        [(ngModel)]="amount" required>