Understanding ASP.Net Validation Controls - The RegularExpressionValidator Control (Page 3 of 4 )
The next Control is the RegularExpressionValidator control. This control makes use of regular expressions, which are a way of describing a string pattern. Regular expressions are out of the scope of this article, so we will bypass this control. Just remember that this control exposes the ValidationExpression property, where you can enter the RegularExpression you want to valid a control against.
There are going to be cases where you need a special way of validate some content: something that the .NET Framework can't offer to you. This is where CustomValidator control comes into play.
As the name implies, this control lets you write the logic for the validation of a control anyway you like. This control exposes an OnServerValidate event that you can use to tie the logic written on the server (such as a function) to the validation control, meaning that the validation will be performed on the server.
Both the server and client validation have to have specific formats. On the server side if you are using C# then the function must return a void and have two parameters: an object argument and a System.Web.UI.WebControls.Custom.ServerValidateEventArgs object.
Here's a function that checks if a number is a pair or not. As you can see, we don't perform any checking in the function about the type of data we are receiving in the argument, since we already saw how to accomplish this using the other Validation controls:
Here you can see that we check if the modulus of the value being passed to the function – if the modulus is zero then it's a pair number. If anything goes wrong the catch block sets the IsValid property to false.
A nicer control is the ValidationSummary control, which doesn't actually perform any validation – this control makes it possible to display all of the error messages in a single place, making a nice layout for your page.
By default all of the validation controls display their error message where the control is placed, so the ValidationSummary control serves as a way of organize the error messages of the controls. Remember, however, that by using the Text property of the controls, you can still mark an astricks in place where an error is and display a more detailed message in the summary control.
If you want to have code reusability in your applications, then you could create a control that contains a textbox for email, a RequiredFieldValidator control, and a RegularExpressionValidator control. You could then put this combination of controls in the VS.NET listbox and use it like a drag 'n drop control in your webforms.
Finally, remember to use the Page.IsValid property before performing any logic, as this property is set on a page when the page uses a validation control. After a PostBack event, this property will be set to true only if the page passed all of the validation logic required.