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 'This name is already taken'.
You’ll often want to use custom validation to validate a control on a webform. Perhaps when a user registers on your website you want to check the database to see if the name he wants to register doesn’t already exist. If you don’t know the basics of form validation, first read the tutorial named ‘Validate using RequiredFieldValidator’.
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.
Now let’s get into the C# code. We won’t bother with a real database in this project, we will replace it with an array that holds 3 names. So in the public class WebForm1 make a string array:
string[] names = {"Van Nostrand", "Vandelay", "Pennypacker"};
Now we’ll use the following code to loop through the array and check to see if the name inside the TextBox matches one of the values in the array:
public void validateName(object sender, ServerValidateEventArgs e)
{
foreach(string name in 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:
…and that’s all! Open the webpage and see for yourself – enter one of the names: ‘Van Nostrand’, ‘Vandelay’ or ‘Pennypacker’ and you’ll get the error:
NOTE It won’t take you much time to realize that this validation is case-sensitive. If you enter vandelay it will validate with no problems. You’ll probably want to change this to case-insensitive. To do that just convert the names from the TextBox in all uppercase or lowercase (using e.Value.ToUpper()) and the text from the database (in this case, arrays) also. |