How to validate integer and float input in an ASP.NET textbox

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

I am using the code below to validate integers and floats in ASP.NET, but if I do not enter decimal then it gives me an error.

 <asp:TextBox ID="txtAjaxFloat" runat="server" />  <cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" TargetControlID="txtAjaxFloat" FilterType="Custom, numbers" ValidChars="." runat="server" /> 

I also have the regular expression from What's a C# regular expression that'll validate currency, float or integer?, but it's giving a validation error if I enter only one value after the decimal..

回答1:

Use ControlValidators.

For example (from the link)

<asp:textbox id="textbox1" runat="server"/> <asp:RangeValidator id="valRange" runat="server"     ControlToValidate="textbox1"     MaximumValue="12/31/1998"     MinimumValue="1/1/1998"     Type="Date"     ErrorMessage="* The date must be between 1/1/1998 and 12/13/1998"     Display="static">*</asp:RangeValidator> > 

The Type attribute can be one of "String", "Integer", "Double", "Date" or "Currency"



回答2:

You can try the following.

<asp:TextBox ID="TextBox2" runat="server" Style="z-index: 103; left: 289px; position: absolute; top: 132px"></asp:TextBox> <cc1:FilteredTextBoxExtender     ID="FilteredTextBoxExtender1"     runat="server"     TargetControlID="TextBox2"     ValidChars="0123456789."> </cc1:FilteredTextBoxExtender> 


回答3:

<asp:RegularExpressionValidator     ID="RegularExpressionValidator6"     runat="server"     ControlToValidate="TBHd"     ValidationExpression="([0-9])[0-9]*[.]?[0-9]*"     ErrorMessage="Invalid Entry"> </asp:RegularExpressionValidator> 


回答4:

How about plain simple parsing? E.g.

int i; if (!int.TryParse(txtAjaxFloat.Text, out i))    i = 0;  float f; if (!float.TryParse(txtAjaxFloat.Text, out f))    f = 0; 

Where 0 is your default "could not validate" value.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!