[Opensource] Quick solution to Form Validation

Raul DAVIDOVICH R.DAVIDOVICH at caconcology.com
Fri Aug 23 01:27:51 PDT 2002


Hello again,

After digging a while inside expresso's classes, I found there is a simple
way to validate forms that correspond to DBObjects.

1) You define the validation rules in the DBObject (many of them are
already set, like null fields.. but this can be overriden). You can also
define masks with the setMask() method
2) The input fields MUST have the same name as the DBObjects fields.
3) You call request.validateDBObject(myDBObject, myErrorCollection). this
in a try/catch block. This method throws two exceptions, a
ControllerException and a ValidationException that must be caught
4) If there are validation errors, the methid
myErrorCollection.getErrorCount will be greater than 0, so there you test
the condition and act accordingly
5) In the JSP, you use the <expresso:ErrorTag/> to show the errors (I
couldn't make it work yet.. I'm still digging).. I'll see if I can manage
to display the errors for each field somehow.. I guess Lirian's API could
be useful for it).. As soon as I'll find why it doesn't work, I'll post the
solution, with the solution to other problems I had with inputs and tags
that could be useful

that's it.

Here is a code example:
...
try{
        MyDBObject dbo = new MyDBObject();
        ErrorColecction errors = new ErrorCollection();

        da.setDBName(params.getDBName());

        try{
        dbo.validateDBObject(dbo, errors);
        }
      catch (ControllerException ce){
        //do something
      }
      catch (ValidationException ve){
        //do something
      }

      if(errors.getErrorCount()==0){
        //the form was ok.. do something
        try{
          transition("nextTransition", params, response);
        }
        catch (NonHandleableException nhe) {
          throw new ControllerException("problem after transition");
        }
      }
      else{
        //the form was wrong.. do something
        try{
          transition("sameTransition", params, response);
        }
        catch (NonHandleableException nhe) {
          throw new ControllerException("problem after transition");
        }
      }
}
catch (DBException dbe){
        //do something
}
...

There are two other methods for validating fields: validateDBField and
validateField.
This last one is the one who does all the job.. so validateDBObject calls
validateDBField for each field, and validateDBField calls validateField.

If the inputs don't have the same name as the fields in the DBObjects, the
form is splitted through several pages and you want to do intermediate
validation, or the form reports to several DBObjects, you can use directly
validateDBField or validateField

Here is the code for these methids (they belong to
com.jcorpotate.expresso.core.controller.ControllerRequest)

/**
     * Convenience method that retrieves parameters/field values and
populates a specified
     * db object. Once the object is populated, the fields are validated
     * and the error collection populated if necessary.
     */
    public void validateDBObject(DBObject oneObject, ErrorCollection ec)
                          throws ControllerException, ValidationException {
        try {
            String oneFieldName = null;

            for (Iterator af = oneObject.getFieldListIterator(); af.hasNext
();) {
                oneFieldName = (String)af.next();
                validateDBField(oneFieldName, oneObject, ec);
            }
        } catch (DBException de) {
            throw new ControllerException(de);
        }
    } /* validateDBObj(DBObject, ErrorCollection) */


    /**
     * Convenience method that retrieves the validates
     * against that one database object field.  Assumes
     * that the parameter name in the request is the same as the
     * DB field name.
     */
    public void validateDBField(String dbFieldName,
                                DBObject oneObject,
                                ErrorCollection ec)
            throws ControllerException, DBException {

            validateField(dbFieldName, dbFieldName, oneObject, ec);
    }


    /**
     * Convenience method that retrieves the validates
     * against that one database object field.
     */
    public void validateField(String dbFieldName,
                                          String reqFieldName,
                                DBObject oneObject,
                                ErrorCollection ec)
            throws ControllerException, DBException {

        Hashtable allParams = getParameters();

        if ((!oneObject.isReadOnly(dbFieldName)) &&
            (!oneObject.isVirtual(dbFieldName))) {
            if (allParams.containsKey(reqFieldName)) {
                String oneFieldParam = getParameter(reqFieldName);

                try {
                    oneObject.checkField(dbFieldName, oneFieldParam);
                } catch (DBException de) {
                    if (log.isInfoEnabled()) {
                        log.info("Validation error for field:", de);
                    }

                    ec.addError(de.getMessage());
                System.out.println("error from validate field" +
de.getMessage());
                }

                oneObject.setField(dbFieldName, oneFieldParam);
            }
        }
    }



hope this will help other people....

Best regards


---------------------------------------------------
Raul Davidovich
Responsable Informatique
Cvitkovic & Associés Consultants

(33) 1 45 15 40 68
(33) 1 45 15 40 41 Fax
-------------------------------------------------------
http://www.caconcology.com





More information about the Opensource mailing list