TOC

The community is working on translating this tutorial into Italian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Validation:

Validation - RegularExpressionValidator

The RegularExpressionValidator is a bit more difficult to write about, because it requires knowledge of Regular Expressions to really use it. However, RegularExpressionValidator is one of the most useful validators, because it can be used to check the validity of any kind of string. If you don't feel like learning Regular Expressions, but still feel like using this validator, have a look around the Internet. You can find many pre-made expressions out there, which can be very useful to you. Here is an example where we require a 4 digit number - nothing else is acceptable:

4 digit number:<br />
<asp:TextBox runat="server" id="txtNumber" />
<asp:RegularExpressionValidator runat="server" id="rexNumber" controltovalidate="txtNumber" validationexpression="^[0-9]{4}$" errormessage="Please enter a 4 digit number!" />
<br /><br />

The only new attribute we use, is the validationexpression. This attribute simply holds the Regular Expression which should be used to validate the field. Since Regular Expressions are beyond the scope of this tutorial, I won't try to explain it, other than it simply tells the validator that a value of 4 digitgs is acceptable, and nothing else. You can use the RegularExpressionValidator for almost everything, for instance validating an e-mail or an URL.

Try switching to Design view and select the RegularExpressionValidator on your page. Now have a look in the Properties tab of Visual Studio. The ValidationExpression attribute has a button next to it, and if you click it, you will gain access to some default expressions, delivered by the ASP.NET team, for various purposes. Just select one of them, to use in your validator.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!