簡體   English   中英

Input type=number Safari 仍然允許帶步進器的字母

[英]Input type=number Safari still allows letters with stepper

我有一個只允許數字的輸入字段

 <input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" pattern="[0-9]+"/>

我設置了比需要更多的參數,只是為了檢查它是否適用於這些參數。 不幸的是它沒有。 當我在Chrome上使用它時,它可以工作,但是當我在Safari上使用它時,它卻沒有。

不幸的是,許多瀏覽器只會在表單提交時驗證帶有type="number"input 在這種情況下,將出現以下提示(以 Safari 為例):

提示輸入數值的 Safari 輸入字段。

我已經修改了您的代碼段以刪除輸入的任何非數字輸入。 我已經測試過此代碼段適用於 Chrome、Firefox 和 Safari。

 <input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />

如果您願意放棄步進器,則可以避免讓單個非數字字符刪除整個輸入:

 <input class="border" type="text" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />

在這些片段中,我們使用:

oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" 

刪除所有會導致input值與典型數字形式不匹配的字符(沒有前導零,不超過一位小數)。

請注意:雖然您可以使用 HTML、CSS 和 JavaScript 來限制用戶在正常使用您的網站時輸入的內容(稱為“客戶端驗證”),但繞過以這種方式設置的限制是微不足道的。

如果您要將此數據發送到服務器進行轉換,則不應相信此數據只是數字形式且具有您期望的形式。 您應該將這種類型的驗證視為純粹為了方便起見,而不是為服務器將接收有效數據提供任何保證。

上面的一系列“替換”對我不起作用。 因為我的項目是在 Angular 中,所以我創建了一個自定義表單字段驗證器。 這樣,在輸入無效時會向用戶顯示錯誤(這會阻止表單提交):

public static numberInputValidator(min: number, max: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (isUndefinedOrEmpty(control?.value) || control.value <= min) {
      return { numberRequired: true };
    } else if(control.value > max) {
      return { numberTooBig: true };
    }
    return null;
  };
}

HTML 輸入字段中唯一相關的屬性是: type="number" step=".01"

要使用它,請將驗證器添加到 FormGroup 中的 FormControl:

myControlName: new FormControl<undefined | number>(undefined, numberInputValidator(0, 100))

即使驗證器只接受number輸入,如果表單字段包含非數字字符,它也會返回numberRequired

然后,如果使用 Angular Material 表單字段,您可以像這樣(在<input>字段之后)顯示自定義錯誤消息:

  <mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberRequired">
    <p>Amount must be greater than zero</p>
  </mat-error>
  <mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberTooBig">
    <p>Amount must be less than or equal to 100</p>
  </mat-error>

暫無
暫無

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

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