簡體   English   中英

輸入僅允許小數點后一位

[英]Input to allow for only one decimal point

我正在嘗試在輸入時格式化數字,在此只能插入有效數字。 除小數點外,我一切正常。 輸入框允許我插入任意數量的小數,但我只想允許一個小數(請參閱最后一個replace() )。

element.oninput = e => {
    let value = e.currentTarget.value;
    let result = value
        // Remove anything that isn't valid in a number
        .replace(/[^0-9-.]/g, '')
        // Remove all dashes unless it is the first character
        .replace(/(?!^)-/g, '')
        // Remove all periods unless it is the last one
        .replace(/(?!)\./g, '');
    element.value = result;
}

https://jsfiddle.net/c4f1L3kv/1/

以下是一些有效的輸入:

123.123
-123.12
123
-123
.123
-.123

以下是一些無效的輸入:

123-123
1-2-3
123.123.123
123-123..12

 var element = document.querySelector('input'); element.oninput = e => { let value = e.currentTarget.value; let result = value .replace(/[^0-9-.]/g, '') .replace(/(?!^)-/g, '') // prevent inserting dots after the first one .replace(/([^.]*\\.[^.]*)\\./g, '$1'); element.value = result; } 
 <input/> 

如果您只想在一個句點字符后接另一個句點字符,則可以使用正向前瞻,例如下面的表達式:

/\.(?=.*\.)/g

說明:

  • \\. -匹配文字. 字符
  • (?= -開始積極的前瞻
    • .*\\. -匹配零個或多個字符,直到一個文字. 字符。
  • ) -正向提前結束

 var element = document.querySelector('input'); element.addEventListener('input', (event) => { event.target.value = event.target.value // Remove anything that isn't valid in a number .replace(/[^\\d-.]/g, '') // Remove all dashes unless it is the first character .replace(/(?!^)-/g, '') // Remove all periods unless it is the last one .replace(/\\.(?=.*\\.)/g, ''); }); 
 <input type="text" /> 


根據您的以下評論:

如果要阻止用戶在字符串末尾添加句點字符(如果已經存在句點字符),則可以使用表達式/(\\..*)\\.$/並替換第一個捕獲組本身,它將有效地刪除捕獲組中未包含的所有內容(即最后一個句號)。

 var element = document.querySelector('input'); element.addEventListener('input', (event) => { event.target.value = event.target.value // Remove anything that isn't valid in a number .replace(/[^\\d-.]/g, '') // Remove all dashes unless it is the first character .replace(/(?!^)-/g, '') // Remove the last period if there is already one .replace(/(\\..*)\\.$/, '$1') // Remove all periods unless it is the last one .replace(/\\.(?=.*\\.)/g, ''); }); 
 <input type="text" /> 

暫無
暫無

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

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