javascript - 如何使用 Jquery 在输入文本框中验证允许减号(-)和仅数字?
问题描述
如何在金额输入字段中进行验证?
在文本框中只允许减号(负号)一次。例如,-10.00。不允许使用其他特殊字符,因为它是一个金额字段。
它不应该允许字母。只允许数字。
Decimal(.) 在文本框中只能出现一次。
解决方案
我刚才是根据你的情况写的,下面测试一下:
更新: 修改为适用于 jquery 和 javascript inline
// This is a middleware that takes as parameter "decimals" which is by default 2
currencyNumber = function(decimals) {
if (typeof decimals !== 'number') {
decimals = 2;
}
return function(e) {
var input = $(this instanceof Window ? e : e.currentTarget);
var value = $.trim(input.val());
var hasNegativeNumber = value.substr(0, 1) === '-' ? '-' : '';
var nextValue = value
.replace(/\.+/g, '.')
.replace(/[^0-9\.]+/g, '');
if (nextValue === '.' || (nextValue.length > 1 && nextValue === "00")) {
nextValue = '';
}
var dotsFound = nextValue.split('.').filter(function(i) {
return i.length;
});
var afterDot = '';
var beforeDot = '';
if (dotsFound.length > 1) {
beforeDot = dotsFound[0];
dotsFound.splice(0, 1);
afterDot = dotsFound.join('');
nextValue = +(beforeDot) + '.' + afterDot.substr(0, decimals);
}
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
input.one('change', function() {
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
nextValue = nextValue.substr(0, nextValue.length - 1);
input.val(hasNegativeNumber + nextValue);
}
$(this).off('change');
})
} else {
input.off('change')
}
input.val(hasNegativeNumber + nextValue);
};
}
// Here is where you call the middleware
$("#amount").on("keyup", currencyNumber(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
Test your number (bind is from jquery):
<input id="amount" type='text' />
<br /> Test your number (bind is from javascript inline):
<input id="amount-inline" onkeyup="currencyNumber(3)(this);" type='text' />
</div>
推荐阅读
- scala - Play framework 2.6 数据库注入
- c# - HTTPModule 部分的 Azure 应用服务配置设置
- scala - 如何在 FUTURE 内发送 ACK?
- java - JPA延迟加载在Spring引导中不起作用
- java - 如何为 StepperLayout 导航按钮定义自定义边距
- vuejs2 - 使用 vee-validate 验证特定数量的输入字段
- python - 如何将两个列表转换为 json 格式
- html - CSS 网格中的缩进
- json - 从 python 脚本打印 json 数据的问题
- android - 我无法从 firebase firestore 获取帖子?