How to check input of integers and float in ASP.NET text field

I use the code below to check for integers and floating point numbers in ASP.NET, but if I don't enter a decimal number, this will result in an error.

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

  

I also have a regex from What is a C # regex that will check for currency, float or integer? but it gives a validation error if I enter only one value after the decimal number.

+3
source share
4 answers

Use ControlValidators .

For example (by reference)

<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>
>

Type "String", "Integer", "Double", "Date" "Currency"

+3

.

<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>
+2
<asp:RegularExpressionValidator
    ID="RegularExpressionValidator6"
    runat="server"
    ControlToValidate="TBHd"
    ValidationExpression="([0-9])[0-9]*[.]?[0-9]*"
    ErrorMessage="Invalid Entry">
</asp:RegularExpressionValidator>
+1
source

How is simple simple parsing? For instance.

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 the default value of "failed to verify."

0
source

Source: https://habr.com/ru/post/1735397/


All Articles