On Mon, 2009-04-27 at 12:16 +0200, Thorsten Scherler wrote:
> Hi all,
>
> I have a question about validating one field with another.
>
> I have a form that ask for the start page and for the end page of an
> article. I need to validate whether the startPage is lesser or equal to
> the endPage.
>
> I could do this in public void onSubmit() {...} of the form like:
> public void onSubmit() {
> if(model.getStartPage()>model.getEndPage()){
> this.error("The startPage cannot be bigger then the endPage");
> }
> ...
> }
>
> However I wonder if that is not cleaner with a validator. My problem is
> ATM that I have not found an example that shows how to validate a field
> comparing it to another field in the same form.
I found a solution. :)
RequiredTextField start = new RequiredTextField("startPage",
Integer.class);
add(start);
RequiredTextField end = new RequiredTextField("endPage",
Integer.class);
MinimumValidator miniVal = new MinimumValidator (start);
end.add(miniVal);
add(end);
I created a small Validator that is doing the comparison and is working
very nicely:
public class MinimumValidator extends AbstractValidator {
private TextField field;
public MinimumValidator(TextField field){
this.field = field;
}
protected Map variablesMap(IValidatable validatable)
{
final Map map = super.variablesMap(validatable);
map.put("field", field);
return map;
}
@Override
protected void onValidate(IValidatable validatable) {
int end = (Integer)validatable.getValue();
int start = Integer.parseInt(field.getValue());
if (start>end){
error(validatable);
}
}
salu2
--
Thorsten Scherler <thorsten.at.apache.org>
Open Source Java <consulting, training and solutions>
Sociedad Andaluza para el Desarrollo de la Sociedad
de la Información, S.A.U. (SADESI)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]