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