Reputation: 16900
As we have comparevalidator in Asp.Net, what do we have in JSF to validate whether two field's value are same or not? I want to validate password and confirmPassword field.
Upvotes: 3
Views: 6019
Reputation: 1109322
No, such a validator does not exist in the basic JSF implementation. You basically need to run the validator on the last component of the group and grab the other component you'd like to validate as well using UIViewRoot#findComponent()
. E.g.
public void validate(FacesContext context, UIComponent component, Object value) {
UIComponent otherComponent = context.getViewRoot().findComponent("otherClientId");
Object otherValue = ((UIInput) otherComponent).getValue();
// ...
}
Also see this article for more background info and concrete examples.
On the other hand, if you're already on JSF2, then you can also make use of ajaxical validation:
<h:form>
<f:event type="postValidate" listener="#{bean.validate}" />
...
</h:form>
..where #{bean.validate}
method look like this:
public void validate(ComponentSystemEvent e) {
UIComponent form = e.getComponent();
UIComponent oneComponent = form.findComponent("oneClientId");
UIComponent otherComponent = form.findComponent("otherClientId");
// ...
}
Also see this article for more JSF2 validation examples.
If you're using JSF utility library OmniFaces, then you could use <o:validateEqual>
. It also allows setting a custom message. The showcase has a live example demonstrating the common usecase of validating the password confirmation. You don't even need ajax to update the model before invoking the validator.
Here's the minimum necessary code:
<h:inputSecret id="password" value="#{signup.person.password}" />
<h:message for="password" />
<h:inputSecret id="confirmPassword" />
<h:message for="confirmPassword" />
<o:validateEqual components="password confirmPassword"
message="Passwords do not match!" showMessageFor="confirmPassword" />
No additional Java code needed.
Upvotes: 8