Custom NotEqualInputValidator in Wicket

Wicket contains many build-in validators for developers, for example, EqualInputValidator, it is best for compare two form components identity. However Wicket’s didn’t provide any validator for not equal validator.

NotEqualInputValidator

Here i take EqualInputValidator as a reference and create a new custom validator called “NotEqualInputValidator”, for not equal comparator for two form components.


package com.mkyong.user;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.util.lang.Objects;

public class NotEqualInputValidator extends AbstractFormValidator {

	private static final long serialVersionUID = 1L;

	/** form components to be checked. */
	private final FormComponent<?>[] components;

	/**
	 * Construct.
	 * 
	 * @param formComponent1
	 *            a form component
	 * @param formComponent2
	 *            a form component
	 */
	public NotEqualInputValidator(FormComponent<?> formComponent1,
			FormComponent<?> formComponent2) {
		if (formComponent1 == null) {
			throw new IllegalArgumentException(
					"argument formComponent1 cannot be null");
		}
		if (formComponent2 == null) {
			throw new IllegalArgumentException(
					"argument formComponent2 cannot be null");
		}
		components = new FormComponent[] { formComponent1, formComponent2 };
	}

	public FormComponent<?>[] getDependentFormComponents() {
		return components;
	}

	public void validate(Form<?> form) {
		// we have a choice to validate the type converted values or the raw
		// input values, we validate the raw input
		final FormComponent<?> formComponent1 = components[0];
		final FormComponent<?> formComponent2 = components[1];

		if (Objects.equal(formComponent1.getInput(), formComponent2.getInput())) {
			error(formComponent2);
		}
	}

}

How to use it?

To use it, just attach it like a normal validator.


	private PasswordTextField passwordTF;
	private PasswordTextField cpasswordTF;

	add(new NotEqualInputValidator(oldpasswordTF,passwordTF));
Note
You may interest to read this “how to create a custom validator in Wicket“.

About the Author

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

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Wicket Tutorialssantosh Recent comment authors
newest oldest most voted
santosh
Guest
santosh

hi,

can u please provide some more examples on wicket which is usefull for beginner like me.

Regards

Santosh M

trackback
Wicket Tutorials

[…] Custom NotEqualInputValidator Another custom validator to make sure two components are not equal. […]