簡體   English   中英

驗證html5輸入類型編號

[英]Validation for html5 input type number

我想針對以下輸入類型顯示2條不同的驗證消息

<input type="number" step="1" formControlName="Ordinal" />

我正在使用具有與此類似的formGroup的反應形式

formBuilder.group({
  ..
  Ordinal: [0, [Validators.required, CustomValidators.integer]],
  ..
});

如果根本沒有輸入,一個Validator Validators.required應該顯示一條必填消息。 如果輸入了無效的號碼,另一個Validator Validator.integer應該顯示一條消息。

Validation.integer的當前實現如下所示

export function integer(control: FormControl) {
  const value = control.value;
  if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value) || value === '' || value === null) {
    return null;
  } else {
    return {
      notNumeric: true
    };
  }
}

我的問題是,在兩種情況下,如果使用type="number" ,瀏覽器都將返回null (當輸入為空/ number無效時)。 我如何區分這兩種狀態?

    to check numeric value I thinks `isNaN and  Number.isInteger()` would be enough 

    Please check the following updated conditions :-


    export function integer(control: FormControl) {
      const value = control.value;
      if(value === 'null' || value === undefined || value === '' ){
       return isRequired: true
      }
     else if ((!Number.isInteger(value) || !isNaN(value))) {
        return null;
      } else {`enter code here`
        return {
          notNumeric: true
        };
      }
    }


    hope this helps

暫無
暫無

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

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