在仅数字输入字段中限制零 [英] Restrict zero in a numeric only input field

查看:60
本文介绍了在仅数字输入字段中限制零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,它只允许输入数字。如何限制输入零(0)作为第一个数字?

This is my code and it it allows to enter digits only. How do I restrict from entering zero (0) as the first digit?

$('.btn').keypress(function(e) {
      var code = e.which;
      if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 8) || (code >= 48 && code <= 57)){
          return true;
        }       
       return false;
    })
    .bind('paste',function(e) {
    e.preventDefault();
});


推荐答案

完成此类工作需要相当多的高级JavaScript。

Doing such work requires quite a bit of advance JavaScript.

首先,您需要知道光标/插入符号是否在位置0.为此,您需要获取选择范围。这取决于您使用的浏览器。

First you need to know whether the cursor / caret is in position 0. To do that you need to get the selection range. That varies depending on the browser you are using.

https://developer.mozilla.org/en-US/docs/Web/API/Range

代码段(未经测试)适用于Firefox& SeaMonkey:

Code snippet (untested) for Firefox & SeaMonkey:

var range = document.createRange();
var pos = range.startOffset;

然后如果pos为零,你知道光标在开始时你可以测试用户是否按下零:

Then if pos is zero, you know the cursor is at the start and you can test whether the user pressed zero:

if(pos == 0 && code == 48)
{
    e.preventDefault();
}

但是,您还要考虑用户输入100和把他的光标或选择包括在1或10中。现在他点击删除,剩下的是一个零(0)。如何处理这种情况将在很大程度上取决于您真正想要在UI中提供的内容。我似乎真的很烦人系统会自动删除其余文本,因为它与有效答案不匹配,没有给你一个解决方法......我相信这不是一个好的解决方案。

However, you want to also think about the case where the user enters 100 and put his cursor or selection to include the 1 or 10. Now he hits delete and what's left is one zero (0). How to handle that case will very much depend on what you really want to offer in your UI. I have seem really annoying systems that would auto-delete the rest of the text because it does not match a valid answer, not giving you a way to fix it... I do believe that's not a good solution.

我通常做的另一个解决方案是让用户输入字段中的任何内容(在您的情况下,只允许数字,但任何随机数),然后当用户单击提交,然后验证格式。如果格式错误,请输出错误。在那种情况下,关于马克思的正则表达式的评论很适用(虽然他在评论中没有解释任何内容,但是很伤心)。

Another solution, which is what I generally do, is to let the user enter whatever in the field (well, in your case, allow for digits only, but any random number), then when the user clicks "Submit", then you verify the format. If the format is wrong, barf out an error. In that case, the comment about regex's by Mate applies well (although he did not explain anything in his comment, kindda sad).

这篇关于在仅数字输入字段中限制零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆