目前我有以下代码

<input type="number" />

结果是这样的

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

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


当前回答

尝试这个选项,并给出最小值和最大值

<输入类型=“数字” 模式=“\d+” 输入模式=“数字” 值=“123” 自动完成=“关闭” 最大长度=“5” 步骤=“1” min=“0” max=“99999” >

其他回答

我在angular中创建了一个指令,强制输入no“-”。

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appPositiveNumber]'
})
export class PositiveNumberDirective {
  private regex = new RegExp(/^\d*[.,]?\d*$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];

  constructor(private el: ElementRef) { }

  @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
    if (!event.key.match(this.regex) && !this.specialKeys.includes(event.key)) {
      event.preventDefault();
      return;
    }
  }
}

所以u可以像这样将它添加到元素上:

<input type="number" appPositiveNumber min="0" step="1" max="9999"
      [(ngModel)]="value.employeeCount">

添加一个min属性

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

这取决于你想要多精确。如果你想只接受整数,那么:

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

例如,如果你想要浮点数,小数点后有两位数字:

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

用这个。

onkeypress="return (event.charCode >= 48 && event.charCode <= 57 || event.charCode == 46)" 

可以输入整数和小数。

(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