簡體   English   中英

輸入類型編號步驟驗證 - 自定義表單驗證

[英]Input type number step validation - Custom form validation

我有一個使用反應形式的 Angular 應用程序。 我的輸入字段之一是 number 類型,我使用step指令來確定有效值,如下所示:

steps = 0.25
myForm: FormGroup

constructor(private fb: FormBuilder) {
  myForm = this.fb.group({
      numberControl: new FormControl(null)
  });

<input type="number" step="{{steps}}" formControlName="numberControl">

可以根據應用程序的其他輸入更改 step 屬性,但為簡單起見,我沒有在本示例中包含該屬性。 我的問題是表格總是有效的。 當我使用輸入字段的向上和向下箭頭鍵時,該步驟有效,但我可以手動輸入任何值並且它仍然有效。

Stackblitz 示例: https ://stackblitz.com/edit/angular-rhyeeb

任何幫助表示贊賞!

您需要自己實現自定義驗證。

import { AbstractControl } from '@angular/forms';

function stepsValidator(control: AbstractControl) {
    if (!control.value || control.value % this.steps !== 0) {
        return { error: true };
    }
    return null;
}

然后在你的 formControl 聲明中

myForm = this.fb.group({
    numberControl: new FormControl(null, this.stepsValidator.bind(this))
});

您必須使用 bind 函數,因為自定義驗證器的作用域與其所在的組件的作用域不同。

默認情況下,numner 輸入字段不會驗證用戶手動輸入的數字是否可被計步器整除。 如果您想要這樣的功能,那么您必須實現一個非常簡單的自定義驗證器。

您所要做的就是創建一個函數來驗證數字輸入字段,然后將新創建的驗證器包含在FormControl對象的 Validators 數組中。 當您的自定義驗證測試通過時,您的驗證器函數應該返回一個null值,或者返回一個詳細說明失敗原因的鍵值對映射。

找到以下代碼片段,演示如何使用自定義驗證器來檢查當前輸入值是否為有效步驟。

export class AppComponent implements OnInit {
  steps = 0.25;
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      numberControl: new FormControl(null, [
        Validators.required,
        this.validateNumField.bind(this)
      ])
    });

    this.myForm.valueChanges.subscribe(_ => {
      if (!this.myForm.valid) {
        console.log('err msg -> ', this.myForm.get("numberControl").errors);
      }
    });
  }

  validateNumField(control: AbstractControl): { [key: string]: any } {
    let rem = control.value && Number.parseFloat(control.value) % this.steps;
    // console.log(rem);

    /**
    * If the remainder is not 0 then user has entered an invalid value
    */
    return rem ? { error: "Not a valid step" } : null;
  }
}

現在,如果不是有效步驟,您的提交按鈕將不起作用。 如果您想使用this.myForm.get("numberControl").errors屬性,您可以繼續並在模板上顯示錯誤消息。

您可以在此處的stackblitz 中找到一個工作示例。 有關自定義驗證的更多信息,請訪問Angular 文檔

編輯:更新答案以捕獲步驟值的變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM