代码之家  ›  专栏  ›  技术社区  ›  B.Balamanigandan

字符串替换为正则表达式十进制验证在Javascript中失败

  •  0
  • B.Balamanigandan  · 技术社区  · 7 年前

    我试图用字符串限制用户输入。使用正则表达式替换。但它失败了,它不允许输入任何字符。请参阅以下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>

    只允许一个点 ). 如果用户输入仅为 或者,如果输入仅为小数部分,则允许 最大8精度 decimal(9,5)

    上述正则表达式无法验证,只允许字符数字和一个句点。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Casimir et Hippolyte    7 年前

    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');