User Interface Validator Pattern


J2EE patterns: User Interface Validator Pattern

  1. User Interface Validator Pattern (30 messages)

    A design pattern for user interface validations that treats the validation rules as data making it easily configurable and maintainable

    Pattern Name
    User Interface Validator

    Treat User Interface validation rules as data thus reducing the development effort for creating user interface validations. The User Interface Validator not only reduces development time but also makes maintainence and bug fixing easy since a change in validation rules only requires a change in the rule data.

    User Interface validations in web applications are done either on the server side or on the client side. The design design decisions are made by the design team of the project.

    In server side validations, each screen will have a server side component in the form of a request handler that will perform the validation as the first step in request handling. The validation will be a series of nested if statements to would perform validations in the appropriate order.

    if (condition-1)
      if (condition-2)
    else if (condition-3)
    else if (condition-4)

    This approach allows each developer to define validations specific to the screen and define the order in which the validations must be carried out.

    The disadvantages to this approach are

    Large amount of if-else code: A typical application can potentially have about 100 screens. On an average, if each screen has about 5 fields, then the amount of if then else is atleast 500. Thus there are 500 opportunities for developing buggy code.

    Bug fix turnaround time: As explained above, bugs are inevitable in this approach. The problem is that to fix each bug, the code has to be changed and then promoted through the various levels of testing and approval before finally deploying on the production system.

    This pattern can be applied for server side validation requirements in web applications. The validation pattern can be implemented on modern application servers and in CGI programs.

    This pattern is applied to minimize the amount of validation code that has to be written for user interface elements. It makes the validation rules as data elements with the validation precendence also part of the data. A rule engine will read the rules from a data store and then apply the rules on the fly based for each screen.

    Participants Name
    Rule: An abstract interface that represents a rule that can be applied for an user interface element on the screen.

    ConcreteRule: A specific implementation of a validation rule rule that is persisted in the data store.

    RuleEngine: Reads rules from the persistent store for a given screen and applies them in the order specified.

    RuleSequence: Defines the order in which the rules have to be executed by the RuleEngine.

    RuleStore: An interface for storing rules and RuleSequence for each screen.

    ConcreteRuleStore: An implementation of the rule store.

    AbstractRequestHandler: The server side processing object for the request from the client. This will run the rule engine for the screen and if the engine validates the rule successfully, forwards a message to the actual request handler.

    ConcreteRequestHandler: Handles the actual server side request. This object when invoked, knows that the base class has already finished all the validations so it can continue with actual request processing.

    ConcreteRequestHandler receives request from the client that is handled by its base class, AbstractRequestHandler.

    The AbstractRequestHander invokes the RuleEngine with the screen identifier and all the data to be validated.

    The RuleEngine requests the ConcreteRuleStore to provide a set of rules that have to be applied for the particular screen and the RuleSequence that defines the order in which the rules have to be applied.

    The RuleEngine applies the rules to the data and returns the result back to the AbstractRequestHandler.

    The AbstractRequestHandler sends different message to its ConcreteRequestHandler based on the results returned by the ConcreteRuleEngine.

    Reduces the number of lines of code thus reducing the number of bugs in the system!

    Makes validation rules available as data thus makes maintainence easier and bug fixing turn around times short

    This pattern is an overkill if the number of screens in the system is not significant. The benefit of code size reduction will be offset by the size of the rule engine and the other associated objects in the pattern.

    The complexity of the DataStore and the RuleEngine increases as the complexity of business validations increases.

    The ConcreteDataStore and the RuleEngine could degrade system performance if poorly written. Since this is part of the user interface experience of the user, poor performance will be clearly and immediately visible as a system flaw.

    Let us consider a typical Web based application that uses a J2EE application server for handling requests, the object that receives and handles request on the server side will be a servlet. Thus the AbstractRequestHandler will have to be derived from HttpServlet and the service() method has to be overriden to perform

    Sample Code and Usage
    /** Filename:
      * The AbstractRequestHandler is derived from HttpServlet and it implements
      * the service method. This object will handle the incoming request, run the
      * RuleEngine on the incoming data and then send a message to its derived self
      * indicating either success or failure of the action.

    public class AbstractRequestHandler extends HttpServlet {

        // Request Handler as defined by HttpServlet. Notice that we have made this
        // final since we dont want any of the derived classes to actually implement a
        // service() method. Instead, control will be passed on to them using the two
        // methods defined below.
        public final void Service (ServletRequest request, ServletResponse response)
            // Get the unique identifier for the screen.
            String ScreenID = getParameter("screenid");

            // Construct a hash table containing the key value pairs of the UI fields
            // and the user entered values. This has to be passed to the RulesEngine
            // With the right screen ID.

            HashMap UIFields;

            RuleEngine REngine = RuleEngine.getInstance();
            REngine.Validate(ScreenID, UIFields);
        // This method will be called by the service() method implementation of this
        // class if the rule engine returns success for all validations.
        protected abstract void ValidationSuccess(ServletRequest request,
                                                ServletResponse response);

        // This method is called by the service() method if the RuleEngine returns a
        // validation failure for one of the rules.
        protected abstract void ValidationFailed(servletRequest request,
                                        ServletResponse response, Rule ruleFailed);


    /** Filename:
     * This is the abstract interface that represents a validation Rule. This
     * interface will be used extensively by the RuleEngine to handle UI
     * validations
    public interface Rule {
            public boolean checkValid();

    /** Filename:
     * The RuleEngine will handle all the rule validations. The sequence of
     * validation is defined by the RuleSequence that the engine obtains from the
     * RuleStore.
    public class RuleEngine {

        /** Construct a RuleEngine. This class would typically be a singleton
         * since there is no reason to have more than one RuleEngine
        public RuleEngine()

        /** The actual validate method that is the entry point for all the users of
         * the class. This method takes the screen ID for which validation has to
         * be done and validates the data that has been passed in. The return
         * value represents the results of the validation that can be used for
         * error reporting if there is an validation error.
        public ValidationResult validate(String ScreenId, HashMap UIData)
            //Assume validation is successful before starting on validation
            ValidationResult ValResult = new ValidationResult(true);

            //Get the RuleStore singleton object.
            RuleStore TheStore = RuleStore.getInstance();
            //Get the Rule sequences for the screen.
            RuleSequence TheSequence = TheStore.getRules(ScreenId);
            //For a given field find out the sequence of rules to be applied
            Rule RuleInSeq[] = TheSequence.getRules(UIData.key());
            //Apply the rules
            for(int i =0;iRuleInSeq.length;i++)
                if (false == RuleInSeq[i].checkValid(UIData.value()))

                    //If a rule failed, set the result object with the necessary
                    ValResult.setStatus(false, RuleInSeq[i]);
            return ValResult;

    Known Uses
    Related Patterns
    The Flyweight pattern can be used to reduce object instantiations of Rule objects thus improving performance.

    Consider using the mediator pattern in the RuleEngine sequencer for complex sequences of business rules. This will reduce the complexity of the individual Rule objects and the RuleEngine itself.

    Threaded Messages (30)

  2. The structure of the pattern is nice. We were having a similar requirement, but in the EJB tier, where we need to find a suitable WorkFlow based on prioritised rules, depending on the current updated status of the Business Entity (Session EJBs wrapping Local Entity EJBs).

    In the code example shown, Perhaps, the method

    public ValidationResult validate(String ScreenId, HashMap UIData)
    could be slightly modified to:

    for(Iterator i = UIData.keySet().iterator(); i.hasNext();){
         //For a given field find out the sequence of rules to be applied
         Rule RuleInSeq[] = TheSequence.getRules(UIData.key());
         //Apply the rules
         for(int i =0;iRuleInSeq.length;i++){
              String status = null;
              if (Rule.SUCCESS != (status = RuleInSeq[i].checkValid(UIData.value()))){
                   //If a rule failed, set the result object with the necessary information
                   ValResult.addStatus(RuleInSeq[i], status);
    return ValResult;

    so that, the next view to the user can hint all the validation errors, at once.
  3. Another "known use": in our product TICL ( which is
    JSP GUI library (server-side UI components + custom tags to place them on a page), we've
    used pretty much that idea do define form validation. You would write
    rules that apply to individual fields or whole forms. Rules are independent
    of each other and can be checked at the client-side or at server-side (as per
    the TICL programmer's request). The rule engine however is quite more
    complex because:

    0) The rules contextual: they operate on a whole form, a single field or
    several fields at once.

    1) Rules can be constrained by fields' values. For example, the rule

    <ticl:validIf verify="afterSubmit" applyTo="cardNumber">
        <ticl:equals fid="paymentMethod">Credit Card</ticl:equals>

    says "the value of the cardNumber field should not be empty if the
    payment method is a credit card".

    2) Something not handled by this pattern: the rule engine provides for
    error handling and reporting, also through the definition of "rules".
    For example:

    <ticl:onInvalid field="cardNumber, phoneNumber">
      <p style="font-color:red"><%=error.getErroMsg() %></p>

    The rule is fired (and hence the body of the tag is executed), everytime
    the 'cardNumber' and 'phoneNumber' fields are invalid, for whatever reason.

    It will be nice to extend this pattern to a mini pattern language (true
    patterns are actually elements of a pattern language, right?) that
    includes error handling at various levels as well as error handling and
  4. User Interface Validator Pattern[ Go to top ]

    Using XML in this way to express a validation requirement is just ugly, don't you think ?

    It's a situation calling for an elegant programmatic style like:-
    if (paymentMethod.equals("CreditCard") && isEmpty(cardNumber)) { setValidity(false); }

    That's fairly directly meaningful to me.
    Non-java types might prefer:-
    if PaymentMethod = "CreditCard" and CardNumber NonEmpty then Reject, which would require you to write a little language interpreter, or something.

    Sorry, but I don't like using XML as a programming language anywhere, including JSP tags, and since that's not a popular point of view I won't go on about it.

    You've got to admit it's an ugly way to express yourself, though. A bit like using numeric machine code to write an assembler program.
  5. User Interface Validator Pattern[ Go to top ]

    I share Tim's dislike for expressing yourself in XML; it's ugly alright.

    Another point I would like to make is about the "pattern": this design addresses no creational, structural or behavioral issues and is not a generic design anyway. A design does not become a "design pattern" just because you can fit it in the design pattern description template.

    By the way, I would implement the "off-the-shelf" GoF Interpreter pattern to build a rule engine.
  6. User Interface Validator Pattern[ Go to top ]


    This pattern is a *perfect example* of a pattern! It might not have been described that way, but it is as generic as you can get. BTW, it has been documented many times before. First, a pattern doesn't have to be "creational", "structural" or "behavioral" just because the GoF categorized them that way. It doesn't even have to be a "design" pattern. You have user interface patterns, analysis patterns, architectural patterns, configuration management patterns, organization patterns, process patterns and what not. In fact, the whole pattern movement in software started out from a theory about the architecture of building by Christopher Alexandre (look up "The Timeless Way of Building" at amazon).

    How would you use Interpreter to build a rule engine? The intent of Interpreter is "Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.".
  7. User Interface Validator Pattern[ Go to top ]

    There is a framework on jakarta projects under commons for validator. Pretty much the same purpose as this pattern. The URL is at
  8. "The intent of Interpreter is 'Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.'"

    Doesn't it ring a bell?

    How is this for a grammar for the motivation code in the pattern description:

    valid-form := condition-1 "and" condition-2 | condition-3 | condition-4

    Which kind of patterns does this "*perfect example*" belong to? Why put it in design pattern description template if it's not one?

    The word "pattern" has unfortunately become a hype, a buzzword. I just don't believe people are discovering patterns with merit on a daily basis; GoF could only come up with 23 patterns in their 4 year continuous effort (1991-1994). Alexander has identified less than 250 patterns (in "A Pattern Language : Towns, Buildings, Construction", the sequel to "The Timeless way of Building") in a field that has been around ever since the mankind got out of caves.

    And yes, I would also couple the Interpreter with Visitors (to implement the operations) to interpret the rules, as Steve has pointed out.
  9. The pattern I am trying to present is that of removing long and tiremsome validation code and instead encapsulating them in data. I had expressed it as a design pattern and in the right template. Now if there is another way of expressing this I am willing to hear you out. Otherwise I will stick to this template since it articulates my pattern well.

    If you want to implement it using visitor and interepreter then you are more than welcome.
  10. Ferhat,

    A rule-engine has nothing to do with parsing and interpreting languages. If you want your rules to be defined in a separate language with its own syntax, then yes, go ahead and use "Interpreter".

    The point of this pattern, its generativity, its patterness, is that the code logic is treated as *data*, decoupled from the main processing logic, and even highly-decoupled within itself.

    Keep in mind that most of the time software patterns make sense only in the context of a particular programming language (or paradigm). The "rule-engine" pattern does not make sense in Prolog for example, as GoF's "Iterator" doesn't make sense in Lisp either.

    I would say that this is a software architectural pattern. Since the distinction between "architecture" and "design" is a bit blured, one could categorize it as a "behavioral design patter" as well.

    I agree that the description of the pattern was not what I would have expected. And "patterns" have become hype, yes. And most of them are without merit (that is why often people post them on public forums for discussion ;).

    BTW, I believe Alexander has identified more than 250 patterns, but has not documented them in his book. And the GoF guys as well (for them I know for sure). There are many practical reasons for that.

    BTW2, the rule-based validation mechanism in our product uses precisely a combination of Interpreter and Visitor ;)

    Lastly, I don't think "pattern theory" discussions are appropriate here, so I'll stop. I'll be glad to continue this conversation if you will, but privately (write to borislav at kobrix dot com).

  11. Boris,
      In most of the sites I have been involved with, the validation rules are encoded in the form of (Horror) Javascript or JSP Java code or tag libraries (as in your product). The one problem I have with this approach is that the rules are "all over the place" ie. the fact that the rule for ccard has to be applied if it is a ccard transaction is built into the JSP. I was thinking of a centrally controlled environment to keep the rules as one advantage of this pattern.
  12. Regarding TICL, the environment is still centrally controlled - it's one rule engine that manages all the rules, regardless of whether they are client-side rules or server-side rules. The tags are there as a convenience, there's an API underneath which one can use instead of the tags.

    Better usability dictactes sometimes that input should be validated at the client-side. One of the good things about TICL, in my opinion, is that the rules are really encoded as validation rules and you can ask the library to apply a rule at the server OR at the client - it will generate the JS code automatically in the latter case. That makes very easy to have the same validation logic, encoded in the same way and not worrying when and how it is performed, regardless of whether you define the rules through tags or API calls..

    A last point - I think, validation is process that generally has to occur at various places, at various times and has to be handled by the appropriate layer. For example, checking that "username" must not be empty in a login form, is really UI validation (an empty username doesn't make sense in a login form) and it should ideally be done at the client. Checking whether a user is a member of the site is really business logic validation and it should be moved there. The concrete credit card example that I gave is again a UI validation problem and it should be handled by people doing UI (ideally at the browser), not by people doing business logic - hence, probably in the JSPs!
  13. Ok, everyone's got a taste for patterns and they differ and I know variety is a good thing. I hope I have not been a bore.

    Vashe zdorovie!
  14. My two cents:

    For validation purposes it is always great to have a mechanism (yeah, pattern, whatever) which covers the 80% of simple field/crossfield rules. However, the mechanism needs to be open enough to cover the 20% of weird validations, business analysts and alike come up with (the smart ones always do).

    So, something like a validate(HttpServletRequest) interface in the form beans works well, where you either call your mechanism (default) or have the weird stuff implemented.

    And if you normalized the servlet request before you validate, you might even call validate(NormalizedRequest) and it works for all those other kinds of requests out there as well, which interface to you app.

    Regarding patterns, I haven't seen much new ones since the GoF ones, they are just called differently or "customized" to J2EE specific needs. This is good, because books like Floyds make a much easier and more understandable read than the Gamma et al ... but in the end, we still have 40 patterns.

  15. User Interface Validator Pattern[ Go to top ]

    I agree that this is not a new pattern. I would probably look at the Visitor pattern to solve this kind of problem.
  16. it is not open source but they will provide you with the source code for the rule processors. it has open rule format in XML-SCHEMA and SQL-DATABASE. you can also build your own check it out at: randy
  17. User Interface Validator Pattern[ Go to top ]


    As far as using XML as a "programming language", I sort of agree with you. It was not meant to be used like that either, it was meant to be manipulated by computer programs. Even most JSP tags don't use it that way, and your point of view is perhaps quite popular. However, it's syntax is quite appealing when it comes to expressing simple, but semantically powerful declarative constructs. If you look at it from that point of view, it's not that ugly. You might not understand what I'm talking about if you have only (or mostly) programmed in imperative languages such Java/C/C++ and the like. "if" & al. constructs are about controlling sequential execution flow. Rule-based programming is a bit different: it lets you say "want you want" instead of "how to do it". Your:

    if (paymentMethod.equals("CreditCard") && isEmpty(cardNumber)) { setValidity(false); }

    says "if the paymentMethod is creditCard and if the cardNumber field is not empty, then set a flag indicating that we have a non-valid field".

    The example of my post says: "the field cardNumber is valid if it's not empty whenever the paymentMethod is CreditCard", which, honestly, looks quite more elegant to me.

    Moreover, if you are using Java, your Java "if" construct would have to be the body of a member function of a class representing a rule (and conforming to some interface) that is added somewhere to a rule engine that will interpret it. Then the "programatic elegance" is completely lost ;)

    Or, if you don't care about rule-based approach to validation, then you end up with all sorts of problems as mentionned in the original post. For example, in TICL you would write in a JSP:

    <t:validIf applyTo="cardNumber, expirationDate, cardType">
     <t:where><t:equals fid="paymentMethod">CreditCard</t:equals></t:where>

    <t:onInvalid applyTo="cardNumber, expirationDate, cardType">
     The field <%= error.getField().getLabel() %> must not be empty.

    That is less than 10 lines of code, that is really all there is to it. Tell me how you would write that in plain Java without a rule-engine, how much code is needed, where is this code located, how is the error reported in the JSP. And how can you add more validation logic without complicating (and possibly introducing bugs in) your code: with rules, you just add another one!

    So no, even without being defensive about our product, honestly I don't think this is an ugly way to express yourself, quite the opposite.
  18. The structure of pattern is good and I thinking to apply same in ejb layer. Can someone post sample code for rulestore, rulesequence, rule etc for staring up.
  19. The structure of pattern is good and I thinking to apply same in ejb layer. Can someone post sample code for rulestore, rulesequence, rule etc for starting up.
  20. User Interface Validator Pattern[ Go to top ]

    The idea of this pattern is nice. But the problem is how can you define the validation rule in configurable manner.For some simple validation, obviously it's easy. but to define the rule for those complicated validation or for said "Cross Fields" validation, I think that's a big job. You have to define your own configuration language, grammar and create your own parser. Be reminded , that's not easy.Even with XML.
  21. User Interface Validator Pattern[ Go to top ]


    What more do you think is needed besides "constrained application of rules"? That is, rules for particular fields (or groups of fields) that apply conextually depending upon other fields' values. As explained in my post above, that is essentially what our product offers - a mini-declarative-rule-language for form field validation based on custom JSP tags (i.e. XML). Please, tell me if you see any shortcomings of that approach so we can make our product better ;)

  22. User Interface Validator Pattern[ Go to top ]

    You guys should look into rules engines.

    Here's a couple of good examples: (JRules) (Blaze Advisor)

    These allow you to manage complex rules using XML, multiple scripting languages, GUI interfaces, etc. You can hot deploy rules (if you pair it with EJB you get free isolation--i.e. your ruleset will stay the same for the duration of a transaction).

    Does anyone know of any open source rules engines?
  23. User Interface Validator Pattern[ Go to top ]

    Here are some links to OpenSource rule engines:
  24. User Interface Validator Pattern[ Go to top ]

    Do check out QuickRules , another commercial Rules Engine. Evaluation available for download from


  25. I had originally posted a link here to my site at but someone actually moved a copy here. This version is not editable but I plan to update this based on the feedback. So please look at the link above for updates.
  26. User Interface Validator Pattern[ Go to top ]

    Another open source form validation framework:

    FormProc []

    Anthony Eden
  27. User Interface Validator Pattern[ Go to top ]

    Excellent Pattern. I had thought through this process at one point and came up with the same solution.

    The problem seems to be that you are splitting validation from data. I prefer to use more complex types in my forms, and use strong type checking. For example: class SSN, class phoneNumber, class Memo class Currency...Each needs to have toString and constructor that takes a string. Each should be serializable as well. You caneven speify the SQL type for each.

    This is the differences between an Object Oriented approach and a functional approach <b>for the API User</b> Yes the Pattern above is OO, but only in it's internal design.

    The functional approach is good if you want everything late bound: The UI, Validation, and DB persistance is all to be defined by a GUI. The OO approach is more appropriate when developing a an API for Java/C++ developers.

  28. Check Out JValidator[ Go to top ]

      We have started a similar project on Bea Codeshare which aims to achieve the following :

           1) Do away with reflection all together as in commons validator or formproc
           2) Make it configurable, pluggable , extendable
           3) Mimimal constraint on resources
           4) Reusable code for swing based standalone application as well as j2ee web applications
           5) Fast , light weight

    Plz check JValidator on bea code share , the details are coming soon
  29. User Input Validaton[ Go to top ]

    Having worked on a number of Java-based consumer application projects, the one commonality I have seen has been universally poor input validation.

    I believe there is tremendous benefit to having a "toolkit" available to ease the difficulty and labor involved in writing good validation. Whether this is a pattern for implementation or a framework depends on the particular requirements of a given project.

    I believe the best mechanism for easy validation is to implement the following:

    1. A simple, compact declarative language for writing the "rules". I would utilize XML for its pervasiveness and readily available tools. I would not make this an all-encompassing language, though. Rather, hit the common validations, namely syntactic rules, dependency rules, and regular expressions. Defer custom or domain specific validations to custom classes referenced in the XML.

    2. Create a framework to assign, parse and then apply these rules to fields. Make it generic, so that it can be applied behind the client, regardless of impl., and on the business logic tier.

    3. Implement plumbing for parsing, prioritizing, assigning constructs for error reporting/recovery, caching, etc.

    This seems to give the best technology-agnostic solution since it does not depend on JSP, EJB, etc. All that's needed is XML, a parser, and some Java.

  30. User Input Validaton[ Go to top ]

    Validation is usually not specified when you get the screens from the graphics design firm. Part of the spec needs to be think through this step by step:

    1) IDentify Fields on the screen
    2) Identify allowable values for each field
    3) Identify what to do on validation failure

    Most UI toolkits allow for this type of validation: (Both ATG and Struts do at least). But If you don't allow the screen real estate for it up front, you won't be able to take advantage of them.

    There are at least two types of validation that I have come across. Field Validation and Form Validation. Field validation is ensuring that an Integer field does not have a Letter. Form validation is ensuring that if Last Name is not specified, Zip Code is. Again, this is part of the design. Both can be supported through toolkits. And if you have a specific validation phase of your process, the ability to link and extend validation can be quite usefull. BTW, It may help to read up on the chain of resposibility and decorator design patterns, as both of these come into play in form validation.

  31. I have applied very similar pattern in my projects over a year ago.

    The concept was evaluating in time and soon we have discovered
    that this is not enough just to validate request parameters
    Servlets spec adds two more types(soureces) of parameters
    Session and Application attributes.
    Some times it is necessary to have a complex validation using all 3 types of parameters.
    Sometimes you can not judge if given parameter is valid or not without using some session data.

    In fact in our system we are supporting just request validation of request parameters and session attributes

    For example if you have splited a process of gathering information into several separate forms you may want to:

    # prohibit skipping a phase (you can for example keep a number of current pahse in the session)
    # some fileds in two different forms may be correlated and cannot be validated separatly
    # etc ...