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.

References

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

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: water ionizer()

  • Pingback: alkaline water machine()

  • Pingback: laane penge nu()

  • Pingback: parking()

  • Pingback: stop parking()

  • Pingback: youporn()

  • Pingback: tvpackages.net()

  • Pingback: check out DIRECTV channels()

  • Pingback: uk online casinos()

  • Pingback: light gloves()

  • Pingback: Bypassing UAE internet censorship()

  • Pingback: kangen water()

  • Pingback: kangen water machine()

  • Pingback: best bottled water()

  • Pingback: water ionizer()

  • Pingback: watch movies online()

  • Pingback: watch movies online()

  • Pingback: watch free movies online()

  • Pingback: watch tv show episodes()

  • Pingback: Google()

  • Pingback: Blue Coaster33()

  • http://www.youtube.com/watch?v=ubOOjC1qX8U 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

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

  • http://www.youtube.com/watch?v=ikOUcNvNbUg 7 Inch Tablet Case With Keyboard

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

  • http://www.youtube.com/watch?v=tdp3E-sJtew 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.

  • http://topelevenbeafootballmanagerhack.blogspot.co.at/ 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.

  • Pingback: Seminario II: HTML5, jQuery, Wicket, Responsive Web Design, Bootstrap | Enginyeria d'Aplicacions()

  • 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

    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.

  • Pingback: Custom NotEqualInputValidator in Wicket()