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:
Post a Comment