使用 javascript 验证带有数字的文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9919252/
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
Validation of textbox with numbers using javascript
提问by kk1076
How to prevent or validate the user entering numbers 6 digits with range (eg: 100000) and two decimal digits in a textbox using javascript ?
I m using onkeypress
event in my textbox my code is:
如何防止或验证用户使用 javascript 在文本框中输入具有范围的 6 位数字(例如:100000)和两位十进制数字?我onkeypress
在我的文本框中使用事件我的代码是:
var txtBudget = document.getElementById('MainContent_txtBudget');
txtBudget.addEventListener('keypress', function (evt)
{
var value = this.value + String.fromCharCode(evt.which);
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(value))
{
evt.preventDefault();
}
},
false);?
回答by Juzer Ali
With HTML5 input type='number'
there is no need to use javascript for this validation. Say for example you want a number between 100,000.00 and 200,000 with two decimal digits, use this in your HTML
使用 HTML5 input type='number'
,无需使用 javascript 进行此验证。比如说你想要一个 100,000.00 到 200,000 之间的数字,有两位十进制数字,在你的 HTML 中使用它
Number: <input type="number" name="number" min="100000.00" max="200000" step='0.01'/>
回答by Ashwini Verma
I wonder why not to use RegularExpression control from Asp.net toolbox. Check out this sample:
我想知道为什么不使用来自 Asp.net 工具箱的 RegularExpression 控件。查看此示例:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1"
runat="server" ValidationExpression="^\d{1,6}(\.\d{1,2})?$" ErrorMessage="Only 6 digit numbers allowed"></asp:RegularExpressionValidator>
And if my ValidationExpression is wrong visit this link for your choice: Find Any Regular Expression
如果我的 ValidationExpression 错误,请访问此链接供您选择:查找任何正则表达式
回答by Pranav
'i guess you want something like this ,
call this function onKeyPress
Event of your textbox
'我想你想要这样的东西,调用onKeyPress
你的文本框的这个函数事件
function test()
{
var obj=document.getElementById('textbox1');
if(obj.value)
{
if(isNaN(obj.value))
{
alert('Please enter only numbers');
return;
}
}
}