Simple form validation in Wicket

I used to add custom FormValidators to forms where multi-field validation was required (like checking if two copies of an entered password match.

However, this approach has some problems – I had to list the dependent components and if some of them were hidden at validation time, the validator didn’t work.

Reading around, I saw the recommendation to use the onValidate() method of the form to do validation and this seems a lot more straightforward.

Here’s a sample wicket form with some validation logic to check if the current password matches and if the two copies of the new password are the same.

final Form form = new Form("form", new CompoundPropertyModel(user)) {
	private static final long serialVersionUID = 1L;

	@Override
	protected void onValidate() {
		super.onValidate();

		User user = model.getObject();
		String current_password_entered = currentPasswordField.getConvertedInput();
		String new_password_entered = newPasswordField.getConvertedInput();
		String confirm_new_password_entered = confirmNewPasswordField.getConvertedInput();

		if (current_password_entered != null
		&& !User.encryptPassword(current_password_entered).equals(user.getPassword()))
			error(getString("current_password_not_correct"));

		if (new_password_entered != null && !new_password_entered.isEmpty()) {
			if (new_password_entered.equals(current_password_entered)) {
				error(getString("new_password_same_as_current_password"));
			} else {
				if (!new_password_entered.equals(confirm_new_password_entered))
					error(getString("new_passwords_dont_match"));
			}
		}
	}
};
add(form);