views:

112

answers:

2

Example XML Rules document:

<user>
  <username>
     <not-null/>
     <capitals value="false"/>
     <max-length value="15"/>
  </username>
  <email>
     <not-null/>
     <isEmail/>
     <max-length value="40"/>
  </email>
</user>

How do I implement this? I'm starting from scratch, what I currently have is a User-class, and a UserController which saves the User object in de DB (through a Service-layer and Dao-layer), basic Spring MVC. I can't use Spring MVC Validation however in our Model-classes, I have to use an XML document so an Admin can change the rules

I think I need a pattern which dynamically builds an algorithm based on what is provided by the XML Rules document, but I can't seem to think of anything other than a massive amount of if-statements.

I also have nothing for the parsing yet and I'm not sure how I'm gonna (de)couple it from the actual implementation of the validation-process.

A: 

Maybe an example would be:

  //PSEUDOCODE
  abstract class Validator {
    Map<String method, Set<Field> fields> validationMap;
    Map<String fieldName, Set<String> errorMessages> validationErrors;

 void parseXML() {
     validationMap.add("notNull", { " 'username', 'JavaPete' ", " 'email', '[email protected]' " }
     validationMap.add("max-length", { " 'username', 'JavaPete', '15' ", ... }
  }

 void validate() {
      for (String method : validationMap.keys) {
           for (Field field : validationMap.get(method) ) {
                 invoke(method, field);
           }
      }
  }

 void notNull(Field field) {
     if (field.getValue() == "") {
          validationErrors.add(field.getFieldName(), "Can't be null!");
     }
  }

Notice I didn't add each Set<> property in the Maps correctly, but it's just to make a point here.

Would this be a valid solution? robust?

JavaPete
+1  A: 

This wheel has been reinvented so many times!

You likely can use Spring MVC validation by implementing Spring's Validator interface, but you may need to implement or find a way to base the validation on rules loaded by another means.

I googled and located many pages describing how to use commons validation in Spring. As a bonus, some describe using valang. If your admin can edit the validation rules prior to deployment, one of these might well suffice.

If you really want to make a home-grown XML business rules, you might want to parse the rules using Apache Digester. You probably want to load the rules into a data structure used by your own implementation of the Spring Validator interface.

If the rules have to be changeable after deploy, you'll of course need to add a mechanism to refresh the rules. But at least Digester will still probably help there.

Don Roby
Hi, thanks for the good references! I needed a solution to change the rules after deployment. I have a current solution now, however I will look into Apache Digester. Thanks again.
JavaPete