2011-09-10 200 views

回答

427

使用min attribute这样的:

<input type="number" min="0"> 
+5

你救了我的一天! \ o/:) – saadk

+1

非常感谢亚伯拉罕。 – pipalia

+3

这里有一个[更可靠的参考资源](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-min)。 –

75

我对@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。

所以这个脚本可以防止输入无效的密钥。

+15

Upvoted,但我认为这将有助于澄清什么关键代码被检查:> 95,<106对应于数字0到9; > 47,<58对应于Number Row上的0至9; 8是Backspace。所以这个脚本阻止了任何键,但是输入了这些键。这是彻底的,但我认为对于本机支持数字输入的浏览器来说可能是过度的,这些输入已经过滤了字母键(除了像“e”这样的可以具有数字含义的字符)。它可能足以防止189(短划线)和109(减)。然后结合'min =“0”'。 –

+0

谢谢。作品:) –

+1

@Manwal它限制使用键盘复制和粘贴数字。并允许我使用鼠标复制粘贴负数。 – Beniton

4

仅供参考:与jQuery可以覆盖在事件的内容负值用下面的代码:

$(document).ready(function(){ 
    $("body").delegate('#myInputNumber', 'focusout', function(){ 
     if($(this).val() < 0){ 
      $(this).val('0'); 
     } 
    }); 
}); 

这并不能取代服务器端验证!

4

@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函数。

如上所述,它也是如此。这只是关于如何解决问题的个人偏好。

12

此代码适合我。能否请您检查:

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

这适用于在尝试键入'-'后清空整个输入不是一个好主意。 – extempl

+4

@extempl听起来像是一个公平的惩罚,用户试图在常识表明没有否定的字段中输入负值。 – Rexford

+0

'''input type =“number”name =“test”min =“0”oninput =“validity.valid ||(value = value.replace(/ \ D +/g,''))”>'' ' - 这将删除所有非数字符号 –

1

这里有一个角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

很好地工作谢谢 –

+0

有没有一种允许粘贴的方法?此外,我改变了正则表达式:/^-?[0-9]+(0.[0-9]*){0,1}$/g允许负数,但它似乎不工作? –

10

对我来说,解决办法是:

<input type="number" min="0" oninput="this.value = Math.abs(this.value)"> 
+1

一旦你使用模式和noformvalidate与角度真的最好的解决方案,因为模型不更新,如果不在范围内。我的情况:'' – sebius

+0

当用户知道默认值为0时,此功能效果最佳。其他智能用户会感到困惑退格按下为什么字段不清除。除此之外,这是最好的解决方案。+ 1 –

3

简单的方法:

<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">

0

该解决方案使包括副本键盘粘贴所有的键盘功能。它可以防止用鼠标粘贴负数。它适用于所有浏览器,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; 
    } 
    }); 
}); 
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">

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

尽管这段代码可以解决这个问题,[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)真的有助于提高你的文章的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 –

+0

虽然这可能是正确的答案,但它缺乏足够的细节。请解释_why_这是否有效。当使用堆栈溢出时,考虑到这是一个_living知识库_,那些不分享知识的答案远没有那么有用。 –

相关问题