你只需要这个:
<form action="/" id="form">
<input pattern="\d{0,5}([,.]\d{1,2})?" title="max 5 digits and 2 decimals">
<button type="submit">submit</button>
</form>
这将允许用户输入任意数量的字符,但在表单验证时,如果 pattern 不满足,表单将失败。
该模式是一个正则表达式,内容如下:0 到 5 个数字字符,可选最多两位小数
另外,如果输入不应该为空,您可以像这样添加 required 属性
<input ... pattern="" required>
如果输入为空,这也会导致验证失败。
当不符合该模式时,浏览器将向用户显示title="" 中的任何内容。
玩弄这个小提琴,这样你就可以看到验证错误是如何呈现的:https://jsfiddle.net/aqohfsrj/2/
另外,如果你想使用 javascript 对输入值做一些事情,我建议绑定到表单的 submit 事件,而不是按钮的单击或输入的 enter-keydown 事件
document.getElementById("form").addEventListener("submit", e => {
// if this code is executed it means the validation passed, otherwise errors
// are displayed to the user and this code is not run.
e.preventDefault(); // <-- to avoid trying to use the form's action i.e. the browser will not navigate.
});
要了解我使用的正则表达式,您可以查看以下 regex101 文件:
https://regex101.com/r/aHLI6u/1
最后推荐一个:
尽量避免maxlength用于验证;很多时候,我不得不在网上填写一张要求信用卡的表格,并且仅限于maxlength="16",这起初听起来是个好主意,但如果你试图从一张便条上复制你的信用卡怎么办你有什么东西,它被存储为5430-0000-1111-2222(带有破折号)。当用户想要的只是粘贴,然后编辑,然后提交时,不允许粘贴比允许的更多的字符感觉很粗鲁。我会让用户根据需要添加尽可能多的内容,以便他们可以就地编辑以删除括号(用于电话)、删除货币符号(用于货币)、删除破折号(用于信用卡)并验证 after 他们已经提交了表单。