Form Validation Design
For my Software Engineering course I am developing a jsp site that contains some large HTML forms. (50+ fields of text, list, combo, radio etc..)
Problem is I can't decide whether I am over thinking everything, or on the right track.
What I have
Class Field - represents an HTML form field. Has name, value, errorMsg
Class FieldList - is a list of Fields (container)
Class Form - Represents a JSP form bean, has a set of FieldLists
Class Constraint - A (validation) constraint on a Field
Class Validator - An adapter design that validates fields
Class StringParser - set of validation functions, isNumeric, isPhoneNumber etc...
Each constraint is a sub-class of the Constraint class.
So basically when I create an HTML form, I extend the Form class, I create a bunch of Field objects for each field in the HTML form. I assign various Constraint objects to each field.
When I validate the form, I pass all the fields to the Validator class. It acts as an Adapter for all the various implementations of Constraint.
It passes the field on to the StringParser, and if validation fails, the resulting error message its set in the Field.
One little anoyance to this is:
to use the jsp setProperty property="*" I need to have same-name variables as html form name as well as getters and setters.
This mean I will have variable and Field object redundancy and the "setter" will have to set both of them.
But really my issue is this:
With this design I will have something like
Field f = new Field("username");
If I scrap the whole design and only keep the StringParser class
then I could create
Hashmap<String, String> errors;
Obviously this second option is a lot less work, and im not too sure yet how re-useable the first option is, or even if its more flexible then the second much more simple example.
public boolean validate()
if (!(username.length >= 5 && username.length <= 20))
errors.put("username", "username must be between 5 and 20 characters");