cod*_*der 9 html validation user-input
我正在制作一个简单的网络应用.在其中的一部分,我已经包含了一个类型="数字"的输入框
<input type="number" min="0">
Run Code Online (Sandbox Code Playgroud)
无论如何,当我在最新的谷歌Chrome浏览器中运行代码时,我也可以输入文字:

我不希望用户能够这样做.我该如何纠正这个?
Tob*_*ias 17
您可以使用JavaScript(例如使用jQuery)仅允许特定字符:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9]/g, '');
// Update value
$(this).val(sanitized);
});
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴.
同样支持浮动:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9.]/g, '');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/, '');
// Update value
$(this).val(sanitized);
});
Run Code Online (Sandbox Code Playgroud)
而这里是另一个小提琴.
更新:虽然您可能不需要这个,但这是一个允许前导减号的解决方案.
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Update value
$(this).val(sanitized);
});
Run Code Online (Sandbox Code Playgroud)
现在是最终解决方案,只允许有效小数(包括浮点数和负数):
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
// Update value
$(this).val(sanitized);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28911 次 |
| 最近记录: |