下面的代码禁用0作为第一个字符#foo.
但是,您可以通过键入123,然后拖动以选择123和放置来绕过此0.(或ctrl+a输入)
有办法阻止这种情况吗?
$('input#foo').keypress(function(e){
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />Run Code Online (Sandbox Code Playgroud)
Sea*_*ell 10
我会处理输入,属性更改和粘贴事件.然后使用正则表达式匹配任何以0开头的内容,并将当前值替换为减去前导0的值.
http://jsfiddle.net/SeanWessell/5qxwpv6h/
$('input ').on('input propertychange paste', function (e) {
var val = $(this).val()
var reg = /^0/gi;
if (val.match(reg)) {
$(this).val(val.replace(reg, ''));
}
});
Run Code Online (Sandbox Code Playgroud)
凯文报告的错误修复/根据佳能的推荐更新:
http://jsfiddle.net/SeanWessell/5qxwpv6h/2/
$('input').on('input propertychange paste', function (e) {
var reg = /^0+/gi;
if (this.value.match(reg)) {
this.value = this.value.replace(reg, '');
}
});
Run Code Online (Sandbox Code Playgroud)