目前我有以下代码

<input type="number" />

结果是这样的

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

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


当前回答

用这个。

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

这个解决方案可能看起来有点多余,但它照顾到了每个方面。

在表单中使用this

<input type="number" min="0" (keypress)="onlyDigits($event)" >

在。ts中定义函数

onlyDigits(event) {
   let code = event.charCode;
   return (code >= 48 && code <= 57);
}

这确保箭头只输入正数。它还可以防止输入任何非数字字符(包括'-','+'和'e')

这取决于你想要的是int还是float字段。下面是这两款游戏的外观:

<input type="number" name="int-field" id="int-field" placeholder="positive int" min="1" step="1">
<input type="number" name="float-field" id="float-field" placeholder="positive float" min="0">

int字段附加了正确的验证,因为它的最小值是1。然而,float字段接受0;为了解决这个问题,你可以添加一个约束验证器:

function checkIsPositive(e) {
  const value = parseFloat(e.target.value);
  if (e.target.value === "" || value > 0) {
    e.target.setCustomValidity("");
  } else {
    e.target.setCustomValidity("Please select a value that is greater than 0.");
  }
}

document.getElementById("float-field").addEventListener("input", checkIsPositive, false);

JSFiddle这里。

注意,这些解决方案都不能完全阻止用户尝试输入无效的输入,但是您可以调用checkValidity或reportValidity来确定用户是否输入了有效的输入。

当然,您仍然应该进行服务器端验证,因为用户总是可以忽略客户端验证。

我已经找到了防止负数的另一种解决方案。

<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">

我在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">