gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:21:17 25 4
gpt4 key购买 nike

我尝试使用正则表达式通过 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 精度。

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

最佳答案

验证和替换是两个不同的任务,您需要先测试该字段,然后最终用某些东西替换。示例:

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

关于javascript - Javascript 中字符串替换为正则表达式十进制验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45187136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com