Html 如果有空格或非数字字符,HTML5 input type=number 值在 Webkit 中是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18677323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:08:15  来源:igfitidea点击:

HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?

javascripthtmlformsvalidationinput

提问by tim peterson

This is strange behavior to me but on Webkit browsers (Chrome/Safari, notFirefox) if I include a space in a string of numbers in an <input type=number>then the valueof that input is empty.

这对我来说是一种奇怪的行为,但在 Webkit 浏览器(Chrome/Safari,而不是Firefox)上,如果我在数字字符串中包含一个空格,<input type=number>则该value输入的值为空。

See this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/5/

看到这个 JSFiddle:http: //jsfiddle.net/timrpeterson/CZZEX/5/

Here's the code:

这是代码:

<input id='withOutspace' type='number' value='123'>
<input id='with_space' type='number' value='123 123'>
<button>click</button>

$('button').click(function(){ 
    alert("withOut:"+$('#withOutspace').val()+" |||| with:"+$('#with_space').val());
});

If you go to this JSFiddle, you'll notice that the with_spaceinput is empty. But if you put it in it a number that has a space or any non-numeric characters, the alert will say that input is empty.

如果你去这个 JSFiddle,你会注意到with_space输入是空的。但是如果你在其中输入一个带有空格或任何非数字字符的数字,警报会说输入是空的。

Obviously, this is a disaster for form validation with credit card numbers, etc. so does anyone have a hack for this?

显然,这对于使用信用卡号等进行表单验证来说是一场灾难。所以有人对此有所了解吗?

回答by tim peterson

The hack is to use type="tel"instead of type="number".

黑客是使用type="tel"而不是type="number".

This solves the 2 main issues:

这解决了2个主要问题:

  1. It pulls up a number keypad on mobile devices
  2. It validates (and is notempty) with numbers or non-numbers as input.
  1. 它在移动设备上拉出一个数字键盘
  2. 它使用数字或非数字作为输入来验证(并且不为空)。

Please see this JSFiddle: http://jsfiddle.net/timrpeterson/CZZEX/6/

请参阅此 JSFiddle:http: //jsfiddle.net/timrpeterson/CZZEX/6/

回答by vladkras

I can suggest two ways. 1. Prevent chars in input

我可以建议两种方法。1. 防止输入字符

# updated to support more numerical characters related
$(window).keydown(function(e) {
  if($('input[type=number]').index($(e.target))!=-1) {
    if(
      ($.inArray(e.keyCode, [48,49,50,51,52,53,54,55,56,57,58,96,97,98,99,100,101,102,103,104,105,8,13,190,189]) == -1) // digits, digits in num pad, 'back', 'enter', '.', '-'
      || (e.keyCode == 190 && $(e.target).val().indexOf(".") != -1) // not allow double dot '.'
      || (e.keyCode == 190 && $(e.target).val().length == 0) // not allow dot '.' at the begining
    ) {
      e.preventDefault();
    }
  }
});

or 2. Change input's type on fly

或 2. 即时更改输入的类型

$('input[type=number]').focus(function() {
    $(this).prop('type', 'text');
});

this allows to put whatever you want and change its type back onblur

这允许放任何你想要的东西并改变它的类型 onblur

$(this).blur(function() {
    $(this).prop('type', 'number');
});

But still you cannot store nonnumerical values in input with type=number, so val()will always return you empty string if it meets char or space.

但是仍然无法使用 type=number 在输入中存储非数字值,因此val()如果遇到字符或空格,将始终返回空字符串。

So, at least you have to remove all garbage with .replace(/[^\d]/g, '')- that means "remove all except numbers" before you change type back

所以,至少你必须删除所有垃圾.replace(/[^\d]/g, '')- 这意味着在你改回类型之前“删除所有除数字”

In my exampleI show both methods + clear input values.

我的示例中,我展示了两种方法 + 清除输入值。

回答by Vincent

A way to control input number is to set it empty on blur when you can't read value

控制输入​​数字的一种方法是在无法读取值时将其设置为空

static formattedDecimalInput(input, maxScale, allowEmpty = true) {
    input = $(input);

    input.on("blur", function(e) {
        var inputVal = input.val();

        if(inputVal != "" || !allowEmpty) {
            if(inputVal == "") {
                inputVal = "0";
            }
            var number = Number(inputVal);
            input.val(number.toFixed(maxScale));    
        } else {
            input.val("");
        }
    });
}

You can formatted it by the way, and if you have invalid char on server side you can send a bad request response.

您可以顺便格式化它,如果服务器端有无效字符,您可以发送错误的请求响应。

If you want a requiered field, you can just check if the input is empty with javascript before your server call

如果你想要一个需要的字段,你可以在你的服务器调用之前用 javascript 检查输入是否为空

It is not really the answer of the initial question but I was looking for a user friendly control for this type of input when I arrived here

这不是最初问题的真正答案,但是当我到达这里时,我正在寻找对此类输入的用户友好控件

回答by Alexander

My hack for this problem includes the following (i use jQuery validators):

我对这个问题的 hack 包括以下内容(我使用 jQuery 验证器):

    $(document).on('keyup', '[type="number"]', function () {
        if (this.validity.badInput) {
            $(this).attr('data-badinput', true);
        }
    });

Later in validator method i do this:

后来在验证器方法中我这样做:

    $.validator.addMethod('isInteger', function (value, element, parameterValue) {
        if ($(element).attr('data-badinput')) {
            //We know nasty browser always clears incorrect input, so empty string will look OK next time
            $(element).removeAttr('data-badinput');
            return false;
        }
        return !value || /^-?\d+$/.test(value);
    });

回答by meagar

You're setting a numeric input field to a string which is not a number. What did you expect to happen? The whole point is that these fields don't allow or accept non-numeric input. They are documentedas only accepting a floating pointvalue.

您将数字输入字段设置为不是数字的字符串。你期望会发生什么?重点是这些字段不允许或接受非数字输入。它们被记录为仅接受浮点值。

There is no "hack" available or required; the solution is to stop using a numberinput field for a value that isn't a number. Credit cards, phone numbers, etc; these things are notnumbers. They contain digits as a subsetof the valid characters, but they also contain completely non-numeric characters like spaces, hyphens and parenthesis. They need to be stored and treated as regular strings.

没有可用或需要的“hack”;解决方案是停止number不是数字的值使用输入字段。信用卡、电话号码等;这些东西不是数字。它们包含数字作为有效字符的子集,但它们也包含完全非数字的字符,如空格、连字符和括号。它们需要被存储并被视为常规字符串。

Use <input type="text"/>.

使用<input type="text"/>.