如何在数字范围内使用验证器?

时间:2019-04-02 11:48:19

标签: html angular typescript validation

我希望recipient变量在1到10之间。我用Validators.min(1)Validators.max(10)尝试了一下,但这没有用。如果用户输入的内容无效,我想为用户返回一条错误消息。

如何正确使用验证器?

TS:

  form: FormGroup;
      id: number;
      sender: number;
      recipient: number;
      amount: number;
      fee: number;

  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<SendTXDialogComponent>,
    @Inject(MAT_DIALOG_DATA) data) {

    this.sender = data.sender;

    this.form = this.fb.group({
      id: [this.id, Validators.required],
      sender: [this.sender, Validators.required],
      recipient: [this.recipient, [Validators.required, Validators.min(1), Validators.max(10)]],
      amount: [this.amount, Validators.required],
      fee: [this.fee, Validators.required],
    });
  }

  ngOnInit() {
  }

  /** This method is used to close the dialog and to send the information back to the component, which
   * called the dialog. **/
  save() {
      this.dialogRef.close(this.form.value);
  }

  /** This method is used to close the dialog. **/
  close() {
    this.dialogRef.close();
  }

HTML:

<div class="example-container">
<h1 mat-dialog-title>Transaktion senden</h1>
<div mat-dialog-content [formGroup]="form">

  <p>Sender</p>
  <div>
    <p matInput placeholder="Sender">{{ sender }}</p>
  </div>

  <mat-form-field hintLabel="Empfänger zwischen 1 und 10">
    <input matInput #input placeholder="Empfänger" formControlName="recipient"
    required min="1" max="10">
  </mat-form-field>

  <mat-form-field hintLabel="Betrag darf Ihr Guthaben nicht überschreiten">
    <input matInput #input placeholder="Betrag" formControlName="amount"
    required>
  </mat-form-field>

  <mat-form-field hintLabel="Je höher die Gebühr, desto wahrscheinlicher und schneller wird Ihre Transaktion gemint">
    <input matInput #input placeholder="Gebühr" formControlName="fee"
    required>
  </mat-form-field>

</div>
<div mat-dialog-actions>
  <button mat-raised-button (click)="close()">Zurück</button>
  <button mat-raised-button (click)="save()" cdkFocusInitial>Senden</button>
</div>
</div>

4 个答案:

答案 0 :(得分:2)

只需在输入中添加type=number

如果它是模板驱动的表单,以向HTML添加模式;

  pattern="^[1-9]?"

答案 1 :(得分:0)

要显示消息,需要捕获并显示错误

在此示例中

            最少1个                                  最多10个                     

答案 2 :(得分:0)

如果您想将数字限制为[1-9],请使用正则表达式模式 难道只有一个数字吗?

Validators.pattern('^[1-9]?');

这可能有效

答案 3 :(得分:0)

只问表格是否有效。

save(): void {
    if(!this.form.valid) {
      this.displayMessage();
    } else {
      // actually save
    }
  }