簡體   English   中英

用正則表達式十進制驗證進行字符串替換在Javascript中失敗

[英]String Replace with Regex Decimal Validation fails in Javascript

我試圖使用正則表達式使用string.replace限制用戶輸入。 但是它失敗了,它不允許輸入任何字符。 請參見以下HTML頁面。

 <!DOCTYPE html> <html> <head> <title>Decimal Validation</title> </head> <body> <p>A function is triggered when the user is pressing a key and on keyup in the input field.</p> <input type="text" maxlength="9" onkeyup="myFunction(this)"> <script> function myFunction(text) { if(text) { text.value = text.value.replace(/^(\\d{0,4}\\.\\d{0,5}|\\d{0,9}|\\.\\d{0,8})/g, ''); } } </script> </body> </html> 

我只需要允許數字和精度(即, 只允許一個點 )。 如果用戶輸入僅是整數,則長度應為9,或者如果輸入僅是小數部分,則允許最大8精度,或者如果混合則允許decimal(9,5) -允許4位數和5精度。

上面提到的正則表達式無法驗證,僅允許char位數字和一個句點。

驗證和替換是兩個不同的任務,您需要先測試該字段,然后再測試以最終替換。 例:

function myFunction(text) {
    if( !/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})$/.test(text.value) ) {
        text.value = ''; // or an other kind of replacement if you need something
                         // more precise
    }
}

請注意,您還可以像這樣重寫模式:

/^(?!\d*\.\d*\.)[\d.]{0,9}$/

要將字符保留在驗證模式的開頭,可以使用以下替換:

text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8}).*/, '$1');

暫無
暫無

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

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