3

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

Community
  • 1
  • 1
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178

5 Answers5

4

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"

Dead account
  • 19,587
  • 13
  • 52
  • 82
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kranthi
  • 41
  • 2
1
<asp:RegularExpressionValidator
    ID="RegularExpressionValidator6"
    runat="server"
    ControlToValidate="TBHd"
    ValidationExpression="([0-9])[0-9]*[.]?[0-9]*"
    ErrorMessage="Invalid Entry">
</asp:RegularExpressionValidator>
famousgarkin
  • 13,687
  • 5
  • 58
  • 74
Logical
  • 310
  • 1
  • 3
  • 13
0

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.

Dead account
  • 19,587
  • 13
  • 52
  • 82
adrianos
  • 1,501
  • 2
  • 18
  • 22
0

we can use CompareValidator with Datatypecheck Operator to checkbox the datatype of the text in the textbox.

<asp:CompareValidator ID="CValid" runat="server" ControlToValidate="txtName" Display="Dynamic" ErrorMessage="Float value required." Operator="DataTypeCheck" SetFocusOnError="True" Type="Double"></asp:CompareValidator>
  • Providing just a piece of code without any comment is not the best practice of answer. Please add a couple of words to your code. – Grigory Zhadko Jul 19 '21 at 06:03