Wicket in Action

Server and client side validation

24 April 2013, by martin-g

Maybe not so well known feature in Wicket is that the form component validators are actually Behaviors, or if they are not then a special adapter is used, so at the end they are stored as a behavior in the component.

Being a behavior gives the validator the chance to be notified when the respective form component is being rendered. And this makes it possible to make a validator that can validate at the server side and to contribute whatever is needed for some client side (JavaScript) library to make the same validation before the request is even made to the server.

At this repo you may find an integration with Parsley.js.

The implementation is in ParsleyValidationBehavior.
This is the base class that does most generic configuration, i.e. set the expected by Parsley data-xyz attributes in the form component markup. Additionally it uses a delegate IValidator that does the server side validation.

The usage is as any other validator in Wicket:

TextField<String> fullName = new TextField<String>("fullname", someModel);
fullName.add(new ParsleyValidationBehavior<String>(EmailValidator.getInstance()).type("email").require(true));

The code above is a bit mouthfull so we can create a specialization class:

public class ParsleyEmailValidator extends ParsleyValidationBehavior<String>
{
    public ParsleyEmailValidator()
    {
        super(EmailAddressValidator.getInstance());

        require(true);
        type("email");
    }
}

and use it like:

TextField<String> fullName = new TextField<String>("fullname", someModel);
fullName.add(new ParsleyEmailValidator());

The project just demostrates how to approach the problem. It does not provide full integration with Parsley.js.
If there is interest the project can be moved to WicketStuff and extended more with your help!

Update: Cedric Gatay extended the demo application with Bean Validation (JSR 303) support: Wicket + JSR_303 + Parsley. Good work, Cedric!

-->