ASP.NET Validators : CustomValidator Control

July 25, 2011 by 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

Strongly Typed PHP - Revisited

May 22, 2016

MVC (Model-View-Controller)

May 17, 2016

HP Recovery partitions, transfer from HDD to SSD

May 16, 2016

Dependency Injection using Ninject and PostSharp

April 26, 2016

Aspect Orientated Programming (AOP) - A Brief look at PostSharp

April 15, 2016

How to become a better programmer.

April 5, 2016

JavaScript Fundamentals - Hoisting

March 22, 2016

Quick and dirty look at ECMAScript 6

March 17, 2016

JavaScript Promises

March 9, 2016

CSS Combinators

March 7, 2016

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

ASP.NET(C#) : Autocomplete TextBox - Part 1 (From Scratch)

Part one of how to create an autocomplete textbox using ASP.NET(C#)
March 27, 2011

Angular   Architecture   ASP.NET   Astronomy   Breaking News   C#   C++   Coding Horrors   Comedy   Cross Browser   CSS   Design Patterns   ES6   Google API   IIS   Integration   JavaScript   Jquery Mobile   Love and War   Microsoft Office   Model View Controller   Ninject   Personal   PHP   PostSharp   SEO   South Africa   SQL   Threading   TypeScript   Visual Basic   XML