简体   繁体   English

如何只允许文本框中的数字?

[英]How To allow only numbers in textbox?

I Want to enter text box just to numbers 我想只输入数字文本框

this type = "number" dont block lettrs at client side 这种类型=“数字”不会阻止客户端的lettrs

@Html.TextBoxFor(m => m.kidsNumber, 
                      new { @class = "textBox1", 
                             @type = "number", 
                             @min = "1", 
                             @max = "30", 
                             @id = "kidsNumber"})

This doesnt block letters at client side and server side 这不会阻止客户端和服务器端的字母

[Range(1, 30, ErrorMessage = "1-30")]
[RegularExpression("([0-3][0-9])", ErrorMessage = "1-30")]
public string kidsNumber { get; set; }

Not sure I understand your question, honestly. 老实说,不确定我理解你的问题。 An input with type "number" will block the input of anything but a number in browsers that support it . 类型为“number”的输入将阻止除支持它的浏览器中的数字之外的任何输入。 Not all browsers support the newer HTML5 input types, and in those that don't, the field will fallback to a regular text input that will accept any character. 并非所有浏览器都支持较新的HTML5输入类型,而在那些不支持的情况下,该字段将回退到将接受任何字符的常规文本输入。 And, of course, it doesn't stop people from jacking with your code using the browser developer tools and such and changing the type from number to text to allow any character. 当然,它并不会阻止人们使用浏览器开发人员工具等代码来使用您的代码,并将类型从数字更改为文本以允许任何字符。

If you want to have a little more control, you can attach a JavaScript event handler that listens to an event like keydown on the field and then regex replace anything that's not a digit, but of course, JavaScript can be disabled or otherwise tampered with. 如果你想要更多的控制,你可以附加一个JavaScript事件处理程序来监听字段上的keydown之类的事件,然后正则表达式替换任何不是数字的东西,但当然,JavaScript可以被禁用或以其他方式被篡改。

Really, your best bet at preventing non-numeric input is to change your property's type from string to something like int . 实际上,防止非数字输入的最佳选择是将属性的类型从string更改为类似int的类型。 If a number can't be parsed from the posted data by the modelbinder, the field will be set to 0 (as the default for an int) or null if you make it a nullable int ( int? ). 如果模型绑定器无法从发布的数据中解析数字,则该字段将设置为0(作为int的默认值),如果使其为可为空的int( int? ),则为null。 Either way, the validation for your Range attribute would kick in and present an error to the user. 无论哪种方式, Range属性的验证都会启动并向用户显示错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM