Html 有什么办法可以防止 input type="number" 获得负值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7372067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to prevent input type="number" getting negative values?
提问by Tural Ali
I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method
我只想获得正值,有什么办法可以防止它只使用 html
请不要建议验证方法
回答by Abraham
回答by Manwal
I was not satisfied with @Abhrabm answerbecause:
我对@Abhrabm 的回答不满意,因为:
It was only preventing negativenumbers from being entered from up/down arrows, whereas user can type negative number from keyboard.
它只是防止负号从上/下箭头被输入,而用户可以从键盘键入负数。
Solution is to prevent with key code:
解决方案是使用关键代码来防止:
// 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>
Clarification provided by @Hugh Guiney:
@Hugh Guiney提供的说明:
What key codes are being checked:
正在检查哪些关键代码:
- 95, < 106 corresponds to Numpad 0 through 9;
- 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.
- 95, < 106 对应数字键 0 到 9;
- 47, < 58 对应于 Number Row 上的 0 到 9;8 是退格。
So this script is preventing invalid key from being entered in input.
因此,此脚本可防止在输入中输入无效密钥。
回答by Renato Machado
For me the solution was:
对我来说,解决方案是:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
回答by Chinmay235
This code is working fine for me. Can you please check:
这段代码对我来说很好用。你能检查一下吗:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
回答by Rouvé
Easy method:
简单的方法:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
回答by ykay says Reinstate Monica
I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:
如果输入负数,我想允许十进制数字而不清除整个输入。这至少在 chrome 中运行良好:
<input type="number" min="0" onkeypress="return event.charCode != 45">
回答by Chris H.
The @Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.
@Manwal 的答案很好,但我喜欢代码行较少的代码,以提高可读性。我也喜欢在 html 中使用 onclick/onkeypress 用法。
My suggested solution does the same: Add
我建议的解决方案也是如此:添加
min="0" onkeypress="return isNumberKey(event)"
to the html input and
到 html 输入和
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
as a javascript function.
作为一个 javascript 函数。
As said, it does the same. It's just personal preference on how to solve the problem.
如上所述,它的作用相同。如何解决问题只是个人喜好。
回答by Hafenkranich
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
仅供参考:使用 jQuery,您可以使用以下代码覆盖 focusout 上的负值:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!
这不会取代服务器端验证!
回答by Sarath Nagesh
Here's an angular 2 solution:
这是一个 angular 2 解决方案:
create a class OnlyNumber
创建一个类 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();
}
}
}
add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app
将 OnlyNumber 添加到 app.module.ts 中的声明中,并在您的应用程序中的任何地方像这样使用它
<input OnlyNumber="true">
回答by Pedro B.
Just adding another way of doing this (using Angular)if you don't wanna dirt the HTML with even more code:
如果您不想用更多代码弄脏 HTML,只需添加另一种方法(使用 Angular):
You only have to subscribe to the field valueChanges and set the Value as an absolute value(taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
您只需要订阅字段 valueChanges 并将 Value 设置为绝对值(注意不要发出新事件,因为这会导致另一个 valueChange 因此递归调用并触发最大调用大小超出错误)
HTML CODE
代码
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
TypeScript CODE(在你的组件中)
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'];
}