Performing Custom Validation in ASP.NET
Demonstrates how to use custom validation on a form by checking to see if a string in a TextBox is not the same with a string from an array (or database), case in which it displays ‘Name Already Exists’.
Start a new ASP .NET Web Application project named customValidation and drag a TextBox, a Button and a CustomValidator to WebForm1.aspx.
Now set the ErrorMessage property of CustomValidator1 to “This name is already taken”. Also set the ControlToValidate property to TextBox1.
Write following C# code in your Code behind file
string[] emp_names = { “Mahesh”, “jerson”, “Narayanan” };
public void validateName(object sender, ServerValidateEventArgs e)
{
foreach (string name in emp_names)
{
if (e.Value == name)
{
e.IsValid = false;
}
}
}
At this time we only need to set the ServerValidate event to validateName. We’ll do this using the Properties window of Visual Studio .NET:
Posted by Mahesh ( Tryangled )