Create custom validator in Wicket

In this tutorial, you will create a custom password validator, and attach it to a password field.

See summary steps to create a custom validator :

1. Implements IValidator.


import org.apache.wicket.validation.IValidator;

public class StrongPasswordValidator implements IValidator<String>{
	...
}

2. Override validate(IValidatable validatable).


public class StrongPasswordValidator implements IValidator<String>{
	...
	@Override
	public void validate(IValidatable<String> validatable) {
	
		//get input from attached component
		final String field = validatable.getValue();
		
	}
}

3. Attached custom validator to form component.


public class CustomValidatorPage extends WebPage {

	public CustomValidatorPage(final PageParameters parameters) {

  	    final PasswordTextField password = new PasswordTextField("password",Model.of(""));
		//attached custom validator to password field
		password.add(new StrongPasswordValidator());
		
		//...
	}

}

Full Example

See following Wicket example to create a custom password validator, and display a error message if password didn’t match a pre-defined pattern.

1. StrongPasswordValidator

A custom password validator.


package com.mkyong.user;

import java.util.regex.Pattern;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

public class StrongPasswordValidator implements IValidator<String> {

	private final String PASSWORD_PATTERN 
                              = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

	private final Pattern pattern;

	StrongPasswordValidator() {
		pattern = Pattern.compile(PASSWORD_PATTERN);
	}

	@Override
	public void validate(IValidatable<String> validatable) {

		final String password = validatable.getValue();

		// validate password
		if (pattern.matcher(password).matches() == false) {

			//Message from key "StrongPasswordValidator.not-strong-password"
			error(validatable, "not-strong-password");
			
		}

	}

	private void error(IValidatable<String> validatable, String errorKey) {
		ValidationError error = new ValidationError();
		error.addMessageKey(getClass().getSimpleName() + "." + errorKey);
		validatable.error(error);
	}

}

File : package.properties


StrongPasswordValidator.not-strong-password = Password required at least ... (omitted)

2. Attach to component

Attach above custom validator to a password field.


package com.mkyong.user;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.Model;

public class CustomValidatorPage extends WebPage {

	public CustomValidatorPage(final PageParameters parameters) {

		add(new FeedbackPanel("feedback"));

		final PasswordTextField password 
                                = new PasswordTextField("password",Model.of(""));

		//attached custom validator to password field
		password.add(new StrongPasswordValidator());

		Form<?> form = new Form<Void>("form") {
			@Override
			protected void onSubmit() {
				info("Done");
			}
		};

		add(form);
		form.add(password);

	}

}

<html>
<head>
<style>
.feedbackPanelERROR {
	color: red;
}
</style>
</head>
<body>
	<h1>Wicket custom validator example</h1>

	<div wicket:id="feedback"></div>
	<form wicket:id="form">
		<p>
			<label>Password</label>: 
                        <input wicket:id="password" type="password" size="20" />
		</p>
		        <input type="submit" value="Register" />
	</form>
		
</body>
</html>

3. Demo

Start and visit – http://localhost:8080/WicketExamples/

Key in a weak password, error message is returned from custom validator and displayed.

Download it – Wicket-Custom-Validator-Example.zip (9KB)

References

  1. Wicket IValidator Javadoc
  2. Wicket PasswordTextField example
  3. RegEx for strong password

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Coba
Guest
Coba

error.addMessageKey() is deprecated. Use error.addKey() instead.

Good tutorial, thanks.

Rafael
Guest
Rafael

Thanks mykong! You saved again.

top eleven hack france
Guest
top eleven hack france

I think this is among the most vital info for me. And i am glad reading your article.
But wanna remark on some general things, The website style is ideal,
the articles is really excellent : D. Good job, cheers

Matias Sanchez
Guest
Matias Sanchez

Its way to complicated, extending just PatternValidator would be easier. Wouldn’t it?

7 Inch Tablet Case With Keyboard
Guest
7 Inch Tablet Case With Keyboard

This is a topic that is close to my heart… Thank you!
Where are your contact details though?

Crown Generator Wizard101
Guest
Crown Generator Wizard101

Attractive section of content. I just stumbled upon your site
and in accession capital to assert that I acquire actually enjoyed account your blog posts.

Anyway I’ll be subscribing to your augment and even I achievement you access consistently fast.

Top Eleven Be a Football Manager Treatment Hack
Guest
Top Eleven Be a Football Manager Treatment Hack

I’ve been exploring for a little bit for any high-quality articles or weblog posts in this kind of space . Exploring in Yahoo I at last stumbled upon this website. Studying this info So i am happy to exhibit that I’ve an incredibly just right uncanny feeling
I discovered just what I needed. I such a lot indisputably will
make sure to don?t overlook this site and give it a
look regularly.

trackback
Seminario II: HTML5, jQuery, Wicket, Responsive Web Design, Bootstrap | Enginyeria d'Aplicacions

[…]  http://wiquery-examples-1-1-x.appspot.com/ , http://wicket.apache.org , http://www.mkyong.com/wicket/create-custom-validator-in-wicket/  y el libro “Enjoying Web Development […]

Ali
Guest
Ali

Good, but if the form and text fields are inside a panel, lets say a tab panel, it does not display the error message

Gabriel
Guest
Gabriel

Very useful tutorial, worked 100%. The only problem I found was when trying to validate blank fields. In that case it returns a null value and it won’t validate. I had to use INullAcceptingValidator and make null and trim().length() == 0 comparisons.

trackback
Custom NotEqualInputValidator in Wicket

[…] NotEqualInputValidator(oldpasswordTF,passwordTF)); Note You may interest to read this "how to create a custom validator in Wicket". #dd_ajax_float{ background:none repeat scroll 0 0 #FFFFFF; border:1px solid #DDDDDD; […]