简体   繁体   English

只允许数字和减号

[英]Allow numbers and minus sign only

I'm trying to allow numbers and a minus sign only in a input type="text" .我试图只在input type="text"允许数字和减号。 I was able to allow numbers only, but I can't allow the minus sign.我只能允许数字,但我不能允许减号。 I tried the following regular expression to allow numbers only:我尝试了以下正则表达式以仅允许数字:

/\D/

When I add the minus sign, it doesn't seem to work:当我添加减号时,它似乎不起作用:

/-?\D/

(The reason I have the question mark (?) is because there won't always be a minus sign.) When I try adding a minus sign to the textfield, it doesn't work. (我有问号 (?) 的原因是因为不会总是有减号。)当我尝试向文本字段添加减号时,它不起作用。 Here's the code:这是代码:

(I tried adding a code snippet, but it wouldn't compile correctly.) (我尝试添加一个代码片段,但它无法正确编译。)

CodePen代码笔

<input id="num" type="text" />

var input = document.getElementById('num');
input.addEventListener("keypress", function(e) {
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (/-?\D/.test(String.fromCharCode(keycode))) { // a non–digit was entered
        e.preventDefault();
    }
});

I suggest using this regex to match a valid number :我建议使用这个正则表达式来匹配一个有效的数字

/^[+-]?\d+$/

and having you logic reversed in test method as this:并让您在test方法中反转逻辑,如下所示:

var input = document.getElementById('num');
input.addEventListener("change", function(e) {
    if (!/^[+-]?\d+$/.test(this.value)) { // a non–digit was entered
    console.log("non-digit was entered");
    $('#num').val('');
    }
});

CodePen代码笔

Try using pattern attribute with RegExp [0-9-]+尝试在RegExp [0-9-]+使用pattern属性

 var input = document.querySelector("input"); input.oninput = function(e) { if (!this.checkValidity()) { // do stuff console.log("invalid input") } }
 input:invalid + label[for="num"]:before { content: "invalid input"; }
 <input id="num" type="text" pattern="[0-9-]+" minlength="1" placeholder="requires input" required /><label for="num"></label>

I think this code allow you to only input numbers and minus sign.我认为这段代码只允许您输入数字和减号。 But because the code also allow "ctrl + c", "ctrl + v", "ctrl + a", etc.., The textfield can be input other characters by "ctrl + v"(paste).但是因为代码中也允许“ctrl+c”、“ctrl+v”、“ctrl+a”等,所以textfield可以通过“ctrl+v”(粘贴)输入其他字符。

If you want to block "ctrl + v"(paste) also, comment out the code below.如果您还想阻止“ctrl + v”(粘贴),请注释掉下面的代码。

 $("#num").on("keydown", function(e){ //character, not with ctrl, alt key if(e.keyCode >= 65 && e.keyCode <= 90 && !e.ctrlKey && !e.altKey) { return false; } // number with shift if(e.keyCode >= 48 && e.keyCode <= 57 && !!e.shiftKey) { return false; } // ` ~ - _ = + \\ | [ { ] } ' " ; : / ? , < . > var otherKeys = [186, 187, 188, 189, 190, 191, 192, 219, 220, 221, 222]; if(otherKeys.indexOf(e.keyCode) !== -1) { // allow minus sign if(e.keyCode === 189 && !e.shiftKey) { return true; } return false; } // if you want to block "ctrl + v"(paste), comment the below code out //if(e.keyCode === 86 && !!e.ctrlKey) { // return false; //} return true; });

\\D refers to non-digits \\D指的是非数字

You were probably thinking of \\d你可能在想\\d

/^-?\d+$/

You are testing against the result of String.fromCharCode(keycode) .您正在针对String.fromCharCode(keycode)的结果进行测试。

This can never be two characters.这永远不能是两个字符。

if (! /-|\d/.test(String.fromCharCode(keycode))) { // a non–digit was entered

The regex /-|\\d/ checks for exactly one character to be either either - or a digit.正则表达式/-|\\d/检查是否只有一个字符是-或数字。

For use in your code example the result of the match is negated with !为了在您的代码示例中使用,匹配结果被否定! . .

As you are testing every single keypress, this will still allow the input to contain - the middle of the value like 123-456-789 .当您测试每个按键时,这仍将允许输入包含-中间值,如123-456-789

After reading all of the suggestions, I'd like you to consider a different approach.阅读完所有建议后,我希望您考虑采用不同的方法。

Reason原因

Your code right now disallows user to modify already inserted input in any way with a keyboard.您的代码现在不允许用户使用键盘以任何方式修改已插入的输入。 Pressing backspace or delete won't work.按退格或删除将不起作用。 Arrows won't work.箭头不起作用。 This does hardly seem as comfortable thing for user.这对用户来说似乎不太舒服。

Suggestion建议

Consider this example:考虑这个例子:

var last = '';
var input = document.getElementById('num');
input.addEventListener('input', function(e){
    if (isNaN(e.target.value))
        e.target.value=last;
    else
        last=e.target.value;
});

CodePen代码笔

Explanation解释

Hooking to event input will allow you to look at the new value of your input field.挂钩事件输入将允许您查看输入字段的新值。 You can check, if it is a number (this also includes floats and negative numbers) by using method isNaN , which takes string and returns true if the input is not a number, false otherwise.您可以使用isNaN方法检查它是否是数字(这也包括浮点数和负数),如果输入不是数字,则该方法接受字符串并返回 true,否则返回 false。 Therefore, if the condition is true (=not a number), you replace the new value with the last correct one (in this case, default was set to '', but could be something like var last = isNaN(e.target.value)?'':e.target.value; (for supporting default values or whatever). Otherwise (the input is indeed a number), you leave the value as it is and record it as last successful.因此,如果条件为真(= 不是数字),则用最后一个正确的值替换新值(在这种情况下,默认值设置为 '',但可能类似于var last = isNaN(e.target.value)?'':e.target.value; (用于支持默认值或其他)。否则(输入确实是一个数字),您将值保持原样并将其记录为最后一次成功。

Benefits are obvious, user is allowed to use keys like arrows, backspace, delete or combinations ctrl+c, ctrl+v, while preserving functionality (wrong input (NaN) is immediately deleted).好处是显而易见的,用户可以使用箭头、退格、删除或组合 ctrl+c、ctrl+v 等键,同时保留功能(错误输入 (NaN) 会立即删除)。

Note笔记

If you want strictly signed integers, with this approach you can always cut off floating point if you detect it in else clause.如果您想要严格有符号的整数,使用这种方法,如果您在 else 子句中检测到浮点数,则始终可以切断浮点数。 Plus, not only isNaN considers .另外,不仅 isNaN 考虑 . (dot, but not a comma) to be valid part of a number, it also allows notations like 1e3. (点,但不是逗号)作为数字的有效部分,它还允许像 1e3 这样的符号。 Check this post for more detail.查看此帖子以获取更多详细信息。

I had the same problem, I wanted to allow only digits and only a leading minus sign, to avoid things like ----89 or -89-0-66 , or empty spaces, or dots, as I needed an integer我遇到了同样的问题,我只想允许数字和前导减号,以避免像----89-89-0-66 ,或空格或点这样的东西,因为我需要一个整数

Obviously, I wanted to allow arrow keys and the delete key as well to edit the input value if needed显然,如果需要,我还希望允许箭头键和删除键编辑输入值

My 5 min working solution with jQuery:我使用 jQuery 的 5 分钟工作解决方案:

<input id="input" type="text">

var input = $('input');
var allowed = [
 37, //left arrow
 39, //right arrow
 8 //delete
];

input.on('keyup', function(e) {

 if (allowed.indexOf(e.keyCode) !== -1) {
   return;
 }

 //remove white spaces and dots as I want integers
 var value = $(this).val().trim().replace(/\./g, '');

 if (isNaN(value)) {

   //check negative number validation
   if (value.substring(0, 1) === '-') {
     value = value.replace(/\D/g, '');
     value = '-' + value;
   } else {
     value = value.replace(/\D/g, '');
   }
 }
 $(this).val(value)
});

Codepen代码笔

The only thing I noticed is when editing on Chrome, the cursor gets at the end of the value after inserting a digit halfway through, it does not happen in Firefox...我唯一注意到的是在 Chrome 上编辑时,光标在中途插入一个数字后到达值的末尾,这在 Firefox 中不会发生......

$("#id").keypress(function(e){
  if (e.which != 46 && e.which != 45 && e.which != 46 &&
    !(e.which >= 48 && e.which <= 57)) {
       return false;
    }
});

this may help you这可能会帮助你

by given below code you can achieve that.通过下面给出的代码,您可以实现这一目标。 given code allow minus (-) sign only on first place.给定的代码只允许在第一位使用减号 (-)。

<pre><code>
 window.onload=function() {
    var input = document.getElementById("TextBoxId");

    input.onkeypress = function(e) {    e = e || window.event;
        var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

        // Allow non-printable keys
        if (!charCode || charCode == 8 /* Backspace */ ) {
            return;
        }

        var typedChar = String.fromCharCode(charCode);

        // Allow numeric characters
        if (/\d/.test(typedChar)) {
            return;
        }

        // Allow the minus sign (-) if the user enters it first
        if (typedChar == "-" && this.value == "") {
            return;
        }

        // In all other cases, suppress the event
        return false;
    };
    }



</code></pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM