[Opensource] Quick solution to Form Validation
Philip J Brown
philip.brown at platinumsolutions.com
Fri Aug 23 06:29:38 PDT 2002
For what it's worth, I have included a code snippet that I use to
display errors in a jsp, followed by an expresso method that shows how
errors are handled in a controller. If you pattern your code off of
these two, I would expect that you'll find success. It is worth noting,
however, that this example does not specifically iterate through
multiple errors... so I'm not necessarily saying that this couldn't
couldn't be improved, rather I'm implying that this may help.
I keep the JSP fragment in it's own file, and then use JSP include
statements to include it in many of the other JSP files in the project.
The include looks like this:
<%@ include file="errorRow.inc" %>
This example assumes that you have create an HTML table and that you are
displaying your errors, if any, as a new row in the table.
(JSP fragmenmt is below)
===============================
<expresso:IfErrorExists>
<tr>
<td>
<hr>
</td>
</tr>
<tr>
<td>
<FONT COLOR="Red">
<expresso:ErrorTag />
</FONT>
</td>
</tr>
</expresso:IfErrorExists>
====================================
Method from
com.jcorporate.expresso.services.validation.ChangePasswordValidator.java
is below
=======================================
public ControllerResponse validated(
Hashtable params,
ControllerRequest request,
ControllerResponse response,
Controller ctlr)
throws AuthValidationException {
// The db context for the user (Note: this is different from the
Validation entry context, which
// could very well be in a different DB context)
String dbname = (String) params.get("db");
// The login name of the user
String loginName = (String) params.get("UserName");
try {
ErrorCollection errors = new ErrorCollection();
response.setControllerClass(
"com.jcorporate.expresso.services.controller.LoginController");
response.setStyle("sendPasswordValidate");
// Make sure that the user with this loginName actually exists
User user = new User();
user.setDBName(dbname);
user.setLoginName(loginName);
if (!user.find()) {
errors.addError("Account \"" + loginName + "\" not found");
}
// Make sure the User record has not been disabled for some
reason
if (errors.empty()) {
if (user.getAccountStatus().equals("D")) {
errors.addError("Account \"" + loginName + "\" has been
disabled");
}
}
// Reset the user's password and send email
if (errors.empty()) {
String password = user.randomPassword();
user.setPassword(password);
user.setAccountStatus("A");
user.update();
StringBuffer msg = new StringBuffer();
msg.append(
response.getString(
"passwdReset",
loginName,
password,
Setup.getValue(request.getDBName(), "CompanyName"),
Setup.getValue(request.getDBName(),
"HomePageURL")));
user.notify(response.getString("passwdResetSubject"),
msg.toString());
}
// If no errors happened so far, just create an Output to state
// the success and what happened
if (errors.empty()) {
Output o =
new Output(
"successMessage",
"Password succesfully reset and email sent to user
\"" + loginName + "\"");
response.add(o);
Transition login = new Transition();
login.setName("promptLogin");
login.addParam(
"controller",
"com.jcorporate.expresso.services.controller.LoginController");
login.addParam("dbContext", dbname);
response.add(login);
Transition register = new Transition();
register.setName("promptRegister");
register.addParam(
"controller",
"com.jcorporate.expresso.services.controller.LoginController");
register.addParam("dbContext", dbname);
response.add(register);
} else {
// Errors happened, add the error collection to the response
response.saveErrors(errors);
}
} catch (DBException dbe) {
throw new AuthValidationException("DB error", dbe);
} catch (LogException le) {
throw new AuthValidationException("Logging error", le);
} catch (ControllerException ce) {
throw new AuthValidationException("Controller error", ce);
}
return response;
}
========================================
I hope this helps.
-Phil
23 at 04:27, Raul DAVIDOVICH wrote:
>
> 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
>
>
> _______________________________________________
> Opensource mailing list
> Opensource at jcorporate.com
> http://mail.jcorporate.com/mailman/listinfo/opensource
> Archives: http://mail.jcorporate.com/pipermail/opensource/
>
More information about the Opensource
mailing list