Remember Old School OO Principle While Using RegularExpressionValidator

I'm sure all of you are frequently using RegularExpressionValidator in your project. But are sure you are not repeating same expression in multiple pages? Is your code impervious to Change? If you are a bit careful while writing code, you can avoid this. And your friend will be 'Inheritance'.

Suppose you are using a RegularExpressionValidator to validate phone number. You may possibly going to write following code block

<asp:RegularExpressionValidator ID="revPhoneNumber" Display="Dynamic" ErrorMessage="Valid phone no required." ControlToValidate="tbPhoneNumber" ValidationExpression="^\d{8,}$" runat="server">*</asp:RegularExpressionValidator>

If you need this Validator in more than one page, then writing the same code block in every page obviously produces code duplication. Moreover if your project manager asks you to allow '+' at the beginning of the phone number then you have to change the regular expression in all pages. That will be surely a painful task for you. You can make your life easy by following approach.

Create your own validator by inheriting RegularExpressionValidator. Assign a regular expression to the ValidationExpression property

namespace TestValidator.Validators
{
    public class PhoneNumberValidator : RegularExpressionValidator
    {
        public PhoneNumberValidator()
        {
            ValidationExpression = "^\\d{8,}$";
        }
    }
}

To use your own PhoneNumberValidator first add this in the Registry
<%@ Register Assembly="TestValidator(Project Name)" Namespace="TestValidator.Validators" TagPrefix="myvalidators" %>

Then use this in the following way

<myvalidators:PhoneNumberValidator ID="revPhoneNumber" Display="Dynamic" ErrorMessage="Valid phone no required." ControlToValidate="tbPhoneNumber" runat="server">*</myvalidators:PhoneNumberValidator>

Now it is a matter of seconds to accomplish what your project manager wants.

3 comments:

Rony April 5, 2011 at 4:27 AM  

Class, Entity, Query, Regular Expression sob jaigatei OO principle apply hochhe :)

Anonymous April 5, 2011 at 4:28 AM  

I have frequently faced similar problems but could not solve it..thanks for sharing experience

Sakhawat April 5, 2011 at 7:00 PM  

Good work. Keep it up.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers