回答
使用min
attribute这样的:
<input type="number" min="0">
我对@Abhrabm answer不满意,因为:
它只能防止负号号码从 上下箭头输入,而用户可以从键盘输入负号。
解决方案是为了防止与键码:由@Hugh Guiney提供
// Select your input element.
var number = document.getElementById('number');
// Listen for input event on numInput.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<form action="" method="post">
<input type="number" id="number" min="0" />
<input type="submit" value="Click me!"/>
</form>
澄清:
什么是被检查的键码:
- 95,< 106对应于数字小键盘0至9;
- 47,< 58对应于Number Row上的0到9;和8是 Backspace。
所以这个脚本可以防止输入无效的密钥。
Upvoted,但我认为这将有助于澄清什么关键代码被检查:> 95,<106对应于数字0到9; > 47,<58对应于Number Row上的0至9; 8是Backspace。所以这个脚本阻止了任何键,但是输入了这些键。这是彻底的,但我认为对于本机支持数字输入的浏览器来说可能是过度的,这些输入已经过滤了字母键(除了像“e”这样的可以具有数字含义的字符)。它可能足以防止189(短划线)和109(减)。然后结合'min =“0”'。 –
谢谢。作品:) –
@Manwal它限制使用键盘复制和粘贴数字。并允许我使用鼠标复制粘贴负数。 – Beniton
仅供参考:与jQuery可以覆盖在事件的内容负值用下面的代码:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
这并不能取代服务器端验证!
@Manwal答案很好,但我喜欢使用较少的代码行来获得更好的可读性。另外我喜欢在html中使用onclick/onkeypress用法。
我建议的解决方案确实是相同的: 添加
min="0" onkeypress="return isNumberKey(event)"
到HTML的输入和
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
的JavaScript函数。
如上所述,它也是如此。这只是关于如何解决问题的个人偏好。
此代码适合我。能否请您检查:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
这里有一个角2的解决方案:
创建一个类OnlyNumber
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumber {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
OnlyNumber添加到声明中app.module.ts和使用像它这样在任何地方在您的应用程序
<input OnlyNumber="true">
很好地工作谢谢 –
有没有一种允许粘贴的方法?此外,我改变了正则表达式:/^-?[0-9]+(0.[0-9]*){0,1}$/g允许负数,但它似乎不工作? –
对我来说,解决办法是:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
一旦你使用模式和noformvalidate与角度真的最好的解决方案,因为模型不更新,如果不在范围内。我的情况:'' – sebius
当用户知道默认值为0时,此功能效果最佳。其他智能用户会感到困惑退格按下为什么字段不清除。除此之外,这是最好的解决方案。+ 1 –
简单的方法:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
该解决方案使包括副本键盘粘贴所有的键盘功能。它可以防止用鼠标粘贴负数。它适用于所有浏览器,codepen上的演示使用bootstrap和jQuery。这应该适用于非英语语言设置和键盘。如果浏览器不支持粘贴事件捕获(IE),它将在聚焦后删除负号。该解决方案的行为与本机浏览器应该使用min = 0 type = number一样。
标记:
<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;
}
});
});
<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">
oninput="this.value=(this.value < Number(this.min) || this.value > Number(this.max)) ? '' : this.value;"
尽管这段代码可以解决这个问题,[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)真的有助于提高你的文章的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 –
虽然这可能是正确的答案,但它缺乏足够的细节。请解释_why_这是否有效。当使用堆栈溢出时,考虑到这是一个_living知识库_,那些不分享知识的答案远没有那么有用。 –
- 1. 有什么办法可以防止Java把我的双重变成指数值?
- 2. 有什么办法可以防止静态变量值碰撞?
- 3. 有没有什么办法可以防止url注入?
- 4. 有什么办法可以防止人们改变ip?
- 5. 有没有什么办法来防止输入事件jquery datepicker
- 6. 有什么办法可以从超类中省略变量吗?
- 7. 有什么办法可以防止在.NET中移动文件?
- 8. 有什么办法可以防止替换JavaScript对象属性?
- 9. 有什么办法可以防止RecyclerView脱离视图?
- 10. 有什么办法可以防止python中的副作用?
- 11. 有什么办法可以防止键盘出现在android
- 12. HTML5:有什么办法可以在输入类型编号中将逗号改成空格吗?
- 13. 有什么办法可以这样吗?
- 14. 有什么办法可以防止m2e修改eclipse .classpath文件吗?
- 15. 有什么办法可以检查一个类型是枚举类型吗?
- 16. 如何防止输入负数或4位以上的数字
- 17. 有什么办法可以防止反应 - 选择(Select.Async)删除未聚焦的搜索输入值?
- 18. 防止输入类型的最大>最大值=数字
- 19. 有什么办法可以防止Mozilla在网址中输入错字时搜索网页?
- 20. 有什么办法可以从父类调用子方法吗?
- 21. 有没有什么办法,输入/ LeaveCriticalSection可以留下
- 22. 有什么办法可以转换这些不可转换的类型吗?
- 23. 有什么方法可以输入另一种类型的Immutable Map吗?例如:
- 24. 有什么办法可以重定向smbclient的输出吗?
- 25. 有什么办法可以从PyQt或PySide自动完成方法和类吗?
- 26. 有什么办法可以插入到int(11)类型的mysql表中双数字吗?
- 27. 有什么办法可以将C++程序转换成ASP.NET吗?
- 28. 有什么办法可以生成级联删除语句吗?
- 29. 有什么办法可以循环变量名吗?
- 30. 有什么办法可以在random.randint中使用raw_input变量吗?
这线程回答了好得多的程度同样的问题:http://stackoverflow.com /问题/ 3 1575496/prevent-negative-inputs-in-form-input-type-number – PiotrWolkowski