本文介绍了禁用零作为< input>中的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码禁用 0 作为 #foo 中的第一个字符。

但是,你可以通过输入 123 来绕过这个,然后拖动选择 123 并输入 0 。 (或输入时 ctrl + a

Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123 and putting 0. (or ctrl+a on input)

有没有办法阻止这种情况?

Is there a way to block this scenario?

 $('input#foo').keypress(function(e){ 
  if (this.value.length == 0 && e.which == 48 ){
   return false;
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />

推荐答案

我会处理输入,属性更改和粘贴事件。然后使用正则表达式匹配任何以0开头的内容,并将当前值替换为减去前导0的值。

I would handle the input, propertychange, and paste events. Then use regex to match for anything that begins with 0 and replace the current value with the value minus the leading 0.

$('input ').on('input propertychange paste', function (e) {
    var val = $(this).val()
    var reg = /^0/gi;
    if (val.match(reg)) {
        $(this).val(val.replace(reg, ''));
    }
});

Kevin报告的错误修复/根据佳能推荐更新:

Bug fix reported by Kevin/Updated per recommendations of canon:

$('input').on('input propertychange paste', function (e) {
    var reg = /^0+/gi;
    if (this.value.match(reg)) {
        this.value = this.value.replace(reg, '');
    }
});

这篇关于禁用零作为&lt; input&gt;中的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:44