ASP.NET Validators : CustomValidator Control

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):
Value was either too large or too small for an Int32
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.

CompareValidator DataType Options

<asp:TextBox runat="server" ID="txtTest"></asp:TextBox>
<asp:CompareValidator ID="validateTest" runat="server" ControlToValidate="txtTest"
    Operator="DataTypeCheck" Type="Integer" ErrorMessage="*"></asp:CompareValidator>

The application expected an Int32 and instead the customer supplied a value that would put any Int64 value to shame, and the validator won't know any better since its validating anything that looks or smells like an integer. (I foolishly assumed it was going to validate Integer(VB)/int(C#)/Int32(CLR) values)

This all makes the CompareValidator a bit mediocre if you're trying to validate actual strongly typed integer based types, e.g. Int32/Int64 etc

In this post I am going to demonstrate how to use the CustomValidator control to validate Int32 values (values between -2147483648 and 2147483647) and at the end of the post we're going to look at how to validate Int64 values.

We're required to provide server and/or client side methods/functions for the CustomValidator control (if you're planning to omit one, rather omit the client side method than the server side - we've got control of our servers, but not necessarily of the browser connecting to the server).

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

The client side function will look something like this:

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

While the server side method will look something like this:

protected void valTest_ServerValidate(object source, ServerValidateEventArgs args)
{
    Int32 result = 0;
    args.IsValid = Int32.TryParse(args.Value, out result);
}

Hooray this will prevent the customer to assign non Int32 values, but what if we need the ability to assign Int64 values? Well, this is where it gets a bit trickier...

The server side method is easy to amend, which will look something like this:

protected void valTest_ServerValidate(object source, ServerValidateEventArgs args)
{
    Int64 result = 0;
    args.IsValid = Int64.TryParse(args.Value, out result);
}

The tricky part comes in when writing the client side validation function,
to quote David Flanagan's JavaScript: The Definitive Guide

The JavaScript number format allows you to exactly represent all integers between -9007199254740992 (-2^53) and 9007199254740992 (2^53), inclusive. If you use integer values larger than this, you may lose precision in the trailing digits.

Int64 values are way above this limitation, e.g between 9223372036854775807 and -9223372036854775808, to demonstrate what David is saying, observe the following snippet:

var x = 9223372036854775807;
var y = 9223372036854775900;

if (x == y) {
	alert("Not cool");
}

In the snippet above x represents a valid Int64 value while y is just too big to be considered an Int64 value, but yet when we compare the two values, javascript seems to think they're equal and we get a message popping up saying "Not cool".

What happend here is the losing of precision mentioned in David's book, infact both values are converted to 9223372036854776000 therefore they are equal.

Luckily the value sent to the javascript callback isn't an integer value, but a string value, which gives us the ability to do a few "tricks", observe the following snippet:

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

Basically we remove leading zeroes (that might exist) and we split the string into javascript manageable integers which we compare to the first 15 digits of our Int64 MaxValue/MinValue and the last remaining digits (if needed).

Leave a Comment



Latest Posts

Enhance Customer Registration Process with Cutting-Edge Solutions from Card Scanning Solutions Inc.

November 4, 2013

JavaScript Threading - Part 2 (Worker)

December 18, 2012

JavaScript Threading - Part 1 (Timers)

December 18, 2012

MS SQL: Parameter Sniffing

May 21, 2012

Solving Cross Browser Issues - Part 3 (Mootools and HTML5)

February 23, 2012

Solving Cross Browser Issues - Part 2 (GWT and Dart)

February 7, 2012

Solving Cross Browser Issues - Part 1 (JQuery and GWT)

January 9, 2012

Be the best stalker you can be

December 13, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 2

November 3, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 1

October 7, 2011


Most Commented on Posts

Moving items between listboxes in ASP.net/PHP example

Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

Cross Browser Issues: Firefox Word Wrapping

Firefox word wrapping issues
June 9, 2008


ASP.NET   C#   C++   Comedy   Cross Browser   Design Patterns   IIS   Integration   JavaScript   Microsoft Office   Personal   PHP   SQL   Threading   Visual Basic   XML