如何在数字范围内使用Validators?

问题描述 投票:0回答:4

我希望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>
html angular typescript validation
4个回答
2
投票

只需将type=number添加到您的输入中

如果它是一个模板驱动的表单来向HTML添加模式;

  pattern="^[1-9]?"

0
投票

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

在这个例子中

Minimum 1 Maximum 10

0
投票

如果你想将数字限制在[1-9]范围内,那么使用正则表达式模式只是单个数字:如果是这样的话

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

这可能有用


0
投票

只要询问表格是否有效。

save(): void {
    if(!this.form.valid) {
      this.displayMessage();
    } else {
      // actually save
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.