Validating Objects Through Metadata
Subject:   Sounds nice, but...
Date:   2006-01-20 12:27:29
From:   dchandler
Response to: Sounds nice, but...

I believe there is a third way to handle validation in a domain-centric way, and it is one of the things I love about JSF. In my managed bean, I've replaced native types like String with a richer type extending ValidatedString. For example,

public static class ReportName extends ValidatedString {
public ReportName(String string) throws ValidatedStringException {
super(string, StringTester.ANS, 20, 1);
private ReportName name;

The ReportName constructor specifies the allowed character set (ANS = alphanumeric + spaces) and min length / max length.

Then I register a custom converter to handle all ValidatedString types in faces-config:


The getAsObject() method of ValidatedStringConverter calls a method on ValidatedString to actually perform the validation.

This way, all validation logic is specified in the domain model, my view template requires no validation tags or rules, and all values on a form get validated, regardless of what kind of component they are bound to.

I've also written Hibernate custom type converters so I can use rich types in my domain model from end-to-end.

Now, I think annotations are a more compact way to express the validation rules than creating an inner class for each property as I've shown above. However, I don't know where I'd hook into JSF to actually run the validation, as the converter wiring depends on the model property extending some class.

Any ideas?

By the way, Ed, I'm a corporate developer, and I grok annotations no problem. In fact, I think it's easier than what I've already done with custom types. I love the richness and extensibility of JSF. I've been doing Web development for 11 years and JSF is the first framework I've seen that makes me feel like I don't need to learn another framework. You guys have absolutely nailed it.

Either way, I think the concerns about needing to modify validation rules at run time are quite valid. In my current project, this is necessary because many of our field defintions are dynamic based on run-time properties. At any rate, I think this indirection is easily done using either annotations or the custom converter approach. Instead of specifying the rule itself, the annotation or custom type would simply contain a key to a rules definition somewhere else.


1 to 1 of 1
  1. Sounds nice, but...
    2006-01-20 13:10:15  dchandler [View]

1 to 1 of 1