Jose R Jose R - 1 year ago 53
ASP.NET (C#) Question

asp net comparevalidator type double datatypecheck allows incorrect values

ASP NET 4.0 on win 7

If I implement a CompareValidator like this:

<asp:CompareValidator ID="cmprValidatorDoubleType" ControlToValidate="TextBox10" Type="Double" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="*Not a valid number." runat="server"></asp:CompareValidator>

It will accept values such as "5." (without the quotation marks) values without decimals. Is this a normal and expected behaviour?

Answer Source

Yes, it is an expected behaviour, as you use the Attribute: Operator here, so firstly the values you enter into textBox will be tried converting implicitly into the Type you defined. i.e. Double here. So, I guess, 5. gets converted to a double value successfully.

MSDN says this about OPERATOR property of CompareValidator:

 A data type comparison of the value entered in the input control being validated and
 the data type specified by the BaseCompareValidator.Type property. Validation fails 
 if the value cannot be converted to the specified data

An integer is always implicitly convertible to any of : long , float, double, or decimal. This is because it is a conversion from smaller to larger data types and there is NO loss of data. See this MSDN link.

Also, When you declare:

Double d = 5;


Double d = Convert.ToDouble("5.");

Check the value of d in debugger. It displayed as: 5.0. So you can now guess that using 5 is actually interpreted as 5.0 and thus the validation passes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download