Sunday 10 February 2008

ASP.NET Custom Validator of ISBN Numbers

International Standard Book Numbers (ISBNs), like other important numbers, such as credit card numbers, lend themselves to self-validation. The last digit of an ISBN is a check digit. A value found by applying a mathematical formula to other digits of the ISBN can be compared to this check digit. If the values relate to each other in a certain way, the ISBN is taken to be of a valid format.

To use an ASP.NET custom validator to apply the validation logic, proceed as follows. (The code validates ten-digit ISBN numbers.)

First, drag a CustomValidator control to the design surface of Visual Studio. Set its ControlToValidate to the ID of the control that is to be validated (eg. a TextBox). Set the ErrorMessage and Text properties as required. Double-click the CustomValidator control and add the following code to the ServerValidate event handler (this is example starter code: you will need to check its suitability against your particular requirements):

protected void cvISBN_ServerValidate( object source,
ServerValidateEventArgs args )
{
string strInput = args.Value;

if( strInput.Length != 10 )
{
args.IsValid = false;
}
else
{
int checksum;

if( strInput[9] == 'X' )
{
checksum = 10;
}
else
{
checksum = (int)strInput[9] - 48;
}

int total = 0;

for( int i = 0; i < 9; i++ )
{
total += ( i + 1 ) * ( (int)strInput[i] - 48 );
}

args.IsValid = ( total % 11 == checksum );
}
}

To perform client-side validation too, you can write a similar function in JavaScript and attach it to the CustomValidator’s ClientValidationFunction property. The function should have the following signature:

function myvalidationfunction(source, args)

No comments: