簡體   English   中英

檢查數值或范圍

[英]Check for numeric value or range

輸入字段可以具有如下值:

23
23-45

不,我想更正值:

string.replace(/[^\d-]/g,'');

但這並不能糾正這些值:

-45
23-
45-23
10-110

所有這些值都不正確(有效值為0-100(因為它們是百分比值),所以110無效)。 因此,在這種情況下,我希望用戶再次查看輸入字段...

我想我必須為這些無效的情況創建第二個RegEx,對嗎?

如果一個百分比由整數表示,則該函數返回true;如果包含破折號,則第一個數字小於第二個,並且兩個數字都在0到100之間:

function isValidPercentage(input) {
    var mat = /^(\d+)(?:-(\d+))?$/.exec(input + "");
    if (mat !== null && ((mat[2] === undefined && mat[1] < 101) || (mat[1] < mat[2] && mat[2] < 101))) {
        return true;
    }
    return false;
}

編輯#1:如果任一數字大於100,則強制錯誤返回

編輯#2:修復錯誤,清理了一下代碼

假設您有一個輸入(#perc)和一個按鈕(#calc),然后嘗試:

document.querySelector('#calc').addEventListener('click', calculate);

function calculate() {
  // replace all non numeric values in the input with nothing
  // and convert it to a Number (using the + operator).
  var value = +(document.querySelector('#perc').value.replace(/[^\d]/g, ''));
  // now you can check the value
  alert( !isNaN(value) && value >= 0 && value <= 100 
            ? 'ok ' + value 
            : 'not ok ' + value );
}

SO-inline代碼插入器無法正常工作,因此您必須自己嘗試一下。

暫無
暫無

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

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