July 25, 2011 by Christoff Truter ASP.NET
This week I had the following wonderful little exception reported by one of our
customers (definitely not ideal):
Now generally I am always careful to put validators on my fields etc and in fact
I did put a validator on this particular field - a CompareValidator set to check
data types like seen below.
<asp:TextBox runat="server" ID="txtTest"></asp:TextBox> <asp:CompareValidator ID="validateTest" runat="server" ControlToValidate="txtTest" Operator="DataTypeCheck" Type="Integer" ErrorMessage="*"></asp:CompareValidator>
<asp:TextBox runat="server" ID="txtTest"></asp:TextBox> <asp:CustomValidator runat="server" ID="valTest" ControlToValidate="txtTest" ErrorMessage="*" ValidateEmptyText="true" OnServerValidate="valTest_ServerValidate" ClientValidationFunction="valTest_ClientValidate"></asp:CustomValidator>
<script type="text/javascript"> function valTest_ClientValidate(sender, e) { e.IsValid = ((!isNaN(parseFloat(e.Value)) && isFinite(e.Value) && ((e.Value % 1) == 0))) && ((e.Value <= 2147483647) && (e.Value >= -2147483648)); } </script>
protected void valTest_ServerValidate(object source, ServerValidateEventArgs args) { Int32 result = 0; args.IsValid = Int32.TryParse(args.Value, out result); }
protected void valTest_ServerValidate(object source, ServerValidateEventArgs args) { Int64 result = 0; args.IsValid = Int64.TryParse(args.Value, out result); }
var x = 9223372036854775807; var y = 9223372036854775900; if (x == y) { alert("Not cool"); }
<script type="text/javascript"> function isInt64(/*string*/value) { if (!isNaN(parseFloat(value)) && isFinite(value) && ((value % 1) == 0)) { value = value.replace(/^[0]+/g, ""); // get rid of possible leading zeroes var limit = 5807; if (value.charAt(0) == "-") { // Make the value positive value = value.substring(1); // Therefore the limit is bigger limit = 5808; } if (value.length > 19) // obviously bigger than Int64 return false; else if (value.length == 19) { // Get manageable value var p = parseFloat(value.substring(0, 15)); if ((p <= 922337203685477) && (value.substring(15) > limit)) { return false; } else if (p > 922337203685477) { return false; } } // Else definitely valid return true; } return false; } function valTest_ClientValidate(sender, e) { e.IsValid = isInt64(e.Value); } </script>