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

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

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

Simple JavaScript Shop - Back to the future : Part 1

March 20, 2015

Getting my hands dirty with TypeScript

February 17, 2015

Quick and dirty look at TypeScript

January 29, 2015

My personal life in review

January 21, 2015

Quick rundown of possible new C# 6.0 features (perhaps, maybe - I think)

January 19, 2015

Proof of Concept - JavaScript Mediator Framework

January 13, 2015

JavaScript Tip - Benchmarking

January 7, 2015

Google's new and improved reCAPTCHA - simple PHP implementation

January 5, 2015

NASA missions to follow in 2015

January 3, 2015

Online content censorship - South Africa

January 2, 2015

Most Commented on Posts

Moving items between listboxes in example

Move items between two listboxes in, 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

Angular   ASP.NET   Astronomy   C#   C++   Coding Horrors   Comedy   Cross Browser   Design Patterns   Google API   IIS   Integration   JavaScript   Love and War   Microsoft Office   Personal   PHP   South Africa   SQL   Threading   TypeScript   Visual Basic   XML