Tuesday,Apr5,

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.

Total Pageviews

Tags

Abstract Entities ActiveMessaging Amazon SQS Asynchronous mail sending Context Menu Contiuous Integration Deploy Rails Application Deployment by Capistrano Design pattern Ext GWT Ext GWT DnD Framework Filter Grid GWT GXT Chart GXT Editable Grid GXT Example GXT Grid Grouping GXT Tree Filter GlassFish Google App Engine Grid GroupLayout JDO JPA JPQL JTable JavaMail API ListView Local Paging Mapped Superclass Open flash chart Reflection Remote pagination Session Management Strategy pattern XTemplate cruisecontrol.rb filter JTable Row flash chart gxt java reCAPTCHA
Twitter Updates
    follow me on Twitter

    Followers