Java Reference
In-Depth Information
4.3
When You Need More: Custom Validation Methods
Sometimes you want to perform validations other than those provided
by the attributes of @Validate . Perhaps the validation is a complex mul-
tistep process that is best implemented in code. Perhaps the validation
requires accessing a database. Whatever the reason, you can imple-
ment a validation using an arbitrary block of code called a validation
method.
By annotating a method in an action bean with @ValidationMethod , you
tell Stripes to invoke it during the validation process. Stripes is pretty
flexible about the signature of the method—you can use any name,
return any type, and throw any exception. The only requirements are
that the method be public and accept either no parameters or one
parameter of type ValidationErrors .
In a validation method, you signal errors by adding them to Validation-
Errors . You can use the object passed to the method if you have included
it as a parameter or obtain it from the action bean context:
@ValidationMethod
public void validateSomething(ValidationErrors errors) {
// Perform validation
// If validation errors occur, add them to 'errors'
}
@ValidationMethod
public void validateSomethingElse() {
// Perform validation
ValidationErrors errors =
getContext().getValidationErrors();
// If validation errors occur, add them to 'errors'
}
To add an error to ValidationErrors , create an object that implements the
ValidationError interface. Stripes offers some ready-to-use implementa-
tions, such as the SimpleError class, which works much like the Sim-
pleMessage class that we've used to display information messages. The
constructor accepts the message string and an optional list of param-
eters. These parameters replace standard Java MessageFormat tokens,
starting at {2} . Indeed, the {0} and {1} tokens are reserved for the name of
the field and the value entered by the user. What's nice is that you can
use {0} and {1} in the message without having to provide those parame-
ters yourself.
 
 
 
Search WWH ::




Custom Search