目前我有以下代码

<input type="number" />

结果是这样的

右边的选择器允许数字变为负数。我该如何预防呢?

我对使用type="number"有疑问,它造成的问题比它解决的要多,我无论如何都要检查它,所以我应该回到使用type="text"吗?


当前回答

<输入类型=“数字” 分钟=“1” 步数=“1”>

其他回答

添加一个min属性

<输入类型=“数字” min=“0”>

试试这个:

Yii2 : Validation rule 

    public function rules() {
    return [
['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
        ];
}

通过在输入标记中添加onkeypress,可以强制输入只包含正整数。

<input type=“number” onkeypress=“return event.charCode >= 48” min=“1” >

在这里,事件。charCode >= 48确保只返回大于或等于0的数字,而min标记确保通过在输入栏内滚动可以得到最小值1。

(function ($) { $.fn.inputFilter = function (inputFilter) { return this.on('input keydown keyup mousedown mouseup select contextmenu drop', function () { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty('oldValue')) { this.value = this.oldValue; //this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ''; } }); }; })(jQuery); $('.positive_int').inputFilter(function (value) { return /^\d*[.]?\d{0,2}$/.test(value); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" class="positive_int"/>

以上代码可以正常工作!!它还可以防止插入超过2个小数点。如果你不需要这个,只要删除\d{0,2},或者如果需要更有限的小数点,只要改变2

在输入类型中添加此代码;

onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57"

例如:

<input type="text" name="age" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />