JSF Validator compare to Strings for Equality - validation

How would you compare two string for equality in a JSF Validator?
if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) {
save = false;
FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null);
}

Use a normal Validator and pass the value of first component as attribute of second component.
<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true"
requiredMessage="Please enter password" validatorMessage="Please enter at least 8 characters">
<f:validateLength minimum="8" />
</h:inputSecret>
<h:message for="password" />
<h:inputSecret id="confirmPassword" required="#{not empty passwordComponent.value}"
requiredMessage="Please confirm password" validatorMessage="Passwords are not equal">
<f:validator validatorId="equalsValidator" />
<f:attribute name="otherValue" value="#{passwordComponent.value}" />
</h:inputSecret>
<h:message for="confirmPassword" />
(note that binding in above example is as-is; you shouldn't bind it to a bean property!)
with
#FacesValidator(value="equalsValidator")
public class EqualsValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object otherValue = component.getAttributes().get("otherValue");
if (value == null || otherValue == null) {
return; // Let required="true" handle.
}
if (!value.equals(otherValue)) {
throw new ValidatorException(new FacesMessage("Values are not equal."));
}
}
}
If you happen to use JSF utility library OmniFaces, then you can use <o:validateEquals> for this. The exact case of "confirm password" is demonstrated on <o:validateEqual> showcase.

Related

How to pass confirmation password validation

I got two password fields at my JSF - and error messages for them, so if confirmation password is not equal to defining password - err message should appears on the screen. But it also appears even if fields are equals but defining password not passed validation (so it passed to confirmation password validator as null)
so - this is my defining password JSF snippet
<div class="item"
style="height: initial">
<p:outputLabel id="l_passDef" for="passDef"
value="#{msgs['customerForm.defaultPassword']}"/>
<p:password id="passDef" widgetVar="passDefVar" value="#{customerBean.customer.password}"
feedback="true" label="Default Password"
redisplay="true" required="true"
requiredMessage="#{msgs['Error.passDef.mandatory']}"
validatorMessage="#{msgs['Error.passDef.wrongFormat']}"
binding="#{passDef}">
<p:ajax event="keyup" oncomplete="hideCustomerErrMsg('passDef')"/>
<f:validateRegex pattern="(?=.{8,})((?=.*\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])).*"/>
</p:password>
<div class="pass-message">
<p:message id="m_passDef" for="passDef" display="text"/>
</div>
</div>
so - this is my confirmation password JSF snippet
<div class="item">
<p:outputLabel id="l_passConf" for="passConf"
value="#{msgs['customerForm.confirmPassword']}"/>
<p:password id="passConf" widgetVar="passConfVar" value="#{customerBean.customer.password}"
label="Confirm Password" redisplay="true" required="true"
requiredMessage="#{msgs['Error.passConf.mandatory']}"
>
<f:attribute value="#{passDef}" name="passDef"/>
<f:validator binding="#{confirmPasswordValidator}"/>
<p:ajax event="keyup" oncomplete="hideCustomerErrMsg('passConf')"/>
</p:password>
<div class="pass-message">
<p:message id="m_passConf" for="passConf" display="text"/>
</div>
</div>
and this is my validator
#Component
#Scope("request")
public class ConfirmPasswordValidator implements Validator {
private static final Logger LOGGER = Logger.getLogger(ConfirmPasswordValidator.class);
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
ResourceBundle resourceBundle = PropertyResourceBundle.getBundle("messages/messages_en");
if (value == null) {
return;
}
UIInput uiInput = (UIInput) component.getAttributes().get("passDef");
String defaultPassword = (String) uiInput.getValue();
String confirmPassword = (String) value;
if ((!confirmPassword.equals(defaultPassword))&&(defaultPassword != null)) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
resourceBundle.getString("Error.passConf.confirm")));
}
}
}
Please help me how to hide err message if password fields are equal but first (defining) password field not passed validation

JSF 1.2 empty <h:selectManyListbox /> validation issue

I'm kind of new to JSF and I'm having trouble to understand what values JSF renders in a form after its validation fails. Im using WebSphere 7 and its default implementation of JSF, MyFaces (I think 2.0).
My xhtml looks like this:
<h:form id="form">
<h:inputText id="text" value="#{backing.text}" required="true"/>
<h:message for="text" />
<h:selectManyListbox id="options" value="#{backing.options}" required="true">
<f:selectItem itemLabel="1" itemValue="1" />
<f:selectItem itemLabel="2" itemValue="2" />
<f:selectItem itemLabel="3" itemValue="3" />
</h:selectManyListbox>
<h:message for="options" />
<h:commandButton value="Save" />
</h:form>
And my backing bean like this:
public class Backing {
private String text;
private String[] options;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String[] getOptions() {
return options;
}
public void setOptions(String[] options) {
this.options = options;
}
}
I fill the <h:inputText /> with some text.
I select two options from the <h:selectManyListbox />
I press the 'Save' button
The form is rendered with the value I entered for <h:inputText /> and with the options I selected on the <h:selectManyListbox /> (no validation messages are shown, as expected)
Now ...
I empty the <h:inputText />
I deselect the two options from the <h:selectManyListbox />
I press the 'Save' button
The form renders the <h:inputText /> empty and the <h:selectManyListbox /> with the previous options I had selected (both validation messages are shown, as expected)
As you can see, the behaviour when rendering the <h:inputText /> and the <h:selectManyListbox /> is different:
<h:inputText /> renders component's submitted value
<h:selectManyListbox /> renders bean's value
I've been trying to render <h:selectManyListbox /> with no options selected without hacking or messing my code, but had no luck.
¿Is this some bug? ¿Am I missing something?
The less hacky solution I found is to copy and re-implement the method renderOption, overriding the default MenuRenderer.
The original source is something like this as I had to decompile (version 1.2_13).
Notice that I'm pasting only the lines that actually need to be changed. If you need to use this solution you will have to copy the full contents of the method:
public class MenuRenderer extends HtmlBasicInputRenderer {
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
boolean containsValue = containsaValue(submittedValues);
if (containsValue) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
I created CustomListboxRenderer (ListboxRenderer extends MenuRenderer) like this:
public class CustomListboxRenderer extends ListboxRenderer {
#Override
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
and then added in faces-config the next lines:
<render-kit>
<renderer>
<component-family>javax.faces.SelectMany</component-family>
<renderer-type>javax.faces.Listbox</renderer-type>
<renderer-class>CustomListboxRenderer</renderer-class>
</renderer>
</render-kit>

Change value of checkbox using ajax in JSF

I try to solve the following problem: i have a group of h:selectBooleanCheckbox that generates using ui:repeat:
<h:form>
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement" varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}"/>
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a"/>
</ui:repeat>
</h:form>
Values and label's text stored in array list and controls by servlet:
#ManagedBean(name="uiCheckboxList")
#ApplicationScoped
public class CheckBoxListBean implements Serializable {
private ArrayList<BoxTuple> list;
// BoxTyple is class with 2 fields - val (double) and enabled (boolean)
public CheckBoxListBean() {
list = new ArrayList<>();
for(double i = -2.0; i <= 2.0; i += 0.5) {
list.add(new BoxTuple(i, false));
}
// Set first element to true
list.get(0).setEnabled(true);
}
public ArrayList<BoxTuple> getList() {
return list;
}
public void setList(ArrayList<BoxTuple> list) {
this.list = list;
}
And my problem is this: when you click on one of the h:selectBooleanCheckbox server asynchronously sent request with information about the changed box, and then change the values of the another boxes without reloading page. In other words, I need to get the behavior of radio boxes. Maybe it sounds silly, but I need to solve this problem. How can i implement this?
You can do something like this:
<h:form id="form">
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement"
varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}" />
<f:ajax render="form"
listener="#{uiCheckboxList.listen(boxElement)}" />
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a" />
</ui:repeat>
</h:form>
(get rid of the varStatus if you don't use it)
public void listen(BoxTuple tuple) {
if (tuple.enabled)
for (BoxTuple t : list)
if (!t.equals(tuple))
t.setEnabled(false);
}

Validate if new value of <h:inputText> is not higher than old value

I want to control the value in an <h:inputText> ..I want that once I leave the input fieldsif I have a higher value than the old value an error message is displayed and I can not validate fields after entering a value lower (the older value is loaded from the database)
I have done somthing like this :
<p:column headerText="Qte" >
<h:inputText value="#{ligne.qte}" styleClass="span12" required="true" valueChangeListener="#{myBean.changeQte}" >
<h:message id="message"></h:message>
<p:ajax event="keyup" listener="#{myBean.onQteChange}" update="message" />
</h:inputText>
</p:column>
in myBean I have this two methods :
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
}
}
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
}
}
Can someone tells me how can I do this because even if I try to make ajax call into my inputtext I have no result ?
You can use :
public void onQteChange(){
String message =null;
int newqte = getQte();
if (newqte > previousQTE ){
message="invalid qte";
FacesContext.getCurrentInstance().addMessage(
"message",new FacesMessage(FacesMessage.SEVERITY_ERROR, message,message));
}
}
<p:column headerText="Qte" >
<h:inputText value="#{ligne.qte}" id="x" styleClass="span12" required="true" valueChangeListener="#{myBean.changeQte}" >
<p:ajax event="keyup" listener="#{myBean.onQteChange}" update="message" />
</h:inputText>
<h:message id="message" for="x" />
</p:column>

How to skip action when validation with a custom validator fails?

I have a small webapplication for a library, with a customized ISBN validator. My .xhtml page for adding a book looks like this:
<fieldset>
<h:messages/>
<ul>
<li>
<h:outputLabel for="isbn" value="#{labels.isbn}:" />
<h:inputText id="isbn" value="#{addController.book.isbn.isbnValue}" required="true" requiredMessage="- ISBN must be filled in.">
<f:validator validatorId="isbnValidator" />
</h:inputText>
</li>
<li>
<h:outputLabel for="title" value="#{labels.title}:" />
<h:inputText id="title" value="#{addController.book.title}" required="true" requiredMessage="- Title must be filled in."/>
</li>
<li>
<h:outputLabel for="name" value="#{labels.name}:" />
<h:inputText id="name" value="#{addController.book.person.name}" required="true" requiredMessage="- Name must be filled in."/>
</li>
<li>
<h:outputLabel for="firstname" value="#{labels.firstname}:" />
<h:inputText id="firstname" value="#{addController.book.person.firstname}" />
</li>
</ul>
<h:commandButton id="addButton" action="#{addController.save}" value="#{labels.add}" />
<h:commandButton id="cancelButton" action="bookOverview" value="#{labels.cancel}" />
</fieldset>
</ui:define>
The isbnValidator of the first input field is this class:
private Isbn isbn;
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
isbn = new Isbn((String) value);
if (!isbn.isIsbn17Characters()) {
addMessageToContext(context, "- ISBN needs to have 17 characters");
}
if (isbn.isIsbn17Characters() && !isbn.isIsbnInRightFormat()) {
addMessageToContext(context, "- Wrong format, it should be like 'XXX-XX-XXX-XXXX-X'");
}
if (isbn.isIsbn17Characters() && isbn.isIsbnInRightFormat() && !isbn.isIsbnFormatValid()) {
addMessageToContext(context, "- ISBN can only contain numbers, and no other tokens");
}
if (isbn.isIsbn17Characters() && isbn.isIsbnInRightFormat() && isbn.isIsbnFormatValid()
&& !isbn.isLastNumberValid()) {
addMessageToContext(context, "- Last number of the ISBN should be " + isbn.getCorrectLastNumber()
+ " with those 12 numbers");
}
}
public static void addMessageToContext(FacesContext context, String message) {
FacesMessage facesMessage = new FacesMessage();
facesMessage.setSummary(message);
facesMessage.setDetail(message);
context.addMessage("isbn", facesMessage);
}
When I click the 'add' button, the book should be added to the database.
When the ISBNfield, namefield or titlefield aren't filled in, I get the corresponding error message. But when my fields are filled in, and the ISBN validation fails, he shows the error message, but he still adds the book (with a wrong ISBN-number) to the database.
A solution which I thought about: If my messages tags is not empty, he shouldn't add the book to the database. But how can I check that?
Or is there a better solution to my problem?
The validation error message handling is wrong. You need to throw a ValidatorException with a FacesMessage instead of adding the FacesMessage manually.
So instead of all those
addMessageToContext(context, "- ISBN needs to have 17 characters");
you need to do
throw new ValidatorException(new FacesMessage("- ISBN needs to have 17 characters"));
This is for JSF sign that the input is invalid and hence the action method won't be invoked. You also don't need to specify the client ID, it will just end up in the <h:message> associated with the input component where this validator is fired on.

Resources