有没有办法防止 input type="number" 接收负数值?

448
我想要获取仅为正数的值,是否有仅使用HTML的方法来防止输入负数?
请不要建议验证方法。

输入控件的屏幕截图


5
这个帖子更详细地回答了同样的问题:https://dev59.com/9FwZ5IYBdhLWcg3wVfAC - PiotrWolkowski
那用户怎么办(而不是开发者)?如果我输入-3,我得到了一个3,这不是我想要的!完全没有意义!只需保留-3并给我一个解释错误。为什么大多数开发人员认为这种可怕的行为是用户友好的呢?当开发人员在不告诉我的情况下破坏我的键盘时,我很讨厌它。 - Cesar
18个回答

3
oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"

2
虽然这段代码可能解决了问题,但附带说明文字真的有助于提高您发布内容的质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您代码建议的原因。 - Sudheesh Singanamalla
虽然这可能是正确的答案,但它缺乏足够的细节。请解释为什么这样做有效。在使用Stack Overflow时,请考虑这是一个“活”知识库,不分享知识的答案远不如有用。 - Marc LaFleur

3

它仍然接受我键盘数字键盘侧的连字符(负号)。只限制/阻止QWERTY键盘上的连字符(负号)按键。 - FAQi

2

如果您不想在HTML中添加更多代码,可以使用Angular来完成此操作的另一种方法:

您只需要订阅字段值的更改并将该值设置为绝对值(注意不要触发新事件,因为这会导致另一个值更改,从而递归调用并触发“最大调用大小超过”错误)

HTML CODE

最初的回答:

<form [formGroup]="myForm">
    <input type="number" formControlName="myInput"/>
</form>

TypeScript 代码(在组件内部)

formGroup: FormGroup;

ngOnInit() { 
    this.myInput.valueChanges 
    .subscribe(() => {
        this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
    });
}

get myInput(): AbstractControl {
    return this.myForm.controls['myInput'];
}

1

<input type="number" name="credit_days" pattern="[^\-]+" 
    #credit_days="ngModel" class="form-control" 
    placeholder="{{ 'Enter credit days' | translate }}" min="0" 
    [(ngModel)]="provider.credit_days"
    onkeypress="return (event.charCode == 8 || event.charCode == 0 || 
    event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 
    57" onpaste="return false">


1

这个答案并不太有用,因为它只能用在上下箭头键,如果你输入-11是不起作用的。所以这里是我使用的一个小修复方法

对于整数使用以下代码

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

当您有价格数字时,请使用此代码

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

0

此解决方案允许使用键盘实现所有功能,包括复制粘贴。它防止使用鼠标粘贴负数。它适用于所有浏览器,并且codepen 上的演示使用了 Bootstrap 和 jQuery。这应该适用于非英语语言设置和键盘。如果浏览器不支持粘贴事件捕获(IE),则在焦点离开后将移除负号。此解决方案的行为与原生浏览器应该是相同的,并且 type=number,min=0。

标记:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

JavaScript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

0
这是一个对于只允许输入数字的数量字段,我认为最好的解决方案。
// Only allow numbers, backspace and left/right direction on QTY input
    if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
        || (e.keyCode > 47 && e.keyCode < 58) // numbers
        || [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
        || (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
        || (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
        || (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
        || (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
    )) {
        return false;
    }

0

If Number is Negative or Positive Using ES6’s Math.Sign

const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1

// ES6 Way
Math.sign(num); // -1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接