Disable validator via ajax - ajax

I have a simple request scoped entity / pojo which has a Enum and a String as properties.
public Enum Type
{
None,
Email,
Fax;
}
#ManagedBean(name = "testEntity")
#RequestScoped
public class TestEntity
{
private Type type; //Default = None
private String address;
//getter and setter
}
This Enum has a field 'Email' which identifies a e-mail address with a related address.
In JSF I now want to enable/disable a validator of a address InputText field regarding the currently selected type in a SelectOneMenu.
<h:form id="formId">
<p:selectOneMenu id="type" value="#{testEntity.type}>
<p:ajax event="change" update=":formId:address"/>
<f:selectItem itemLabel="E-mail" itemValue="Email"/>
<f:selectItem itemLabel="Fax" itemValue="Fax"/>
</p:selectOneMenu>
<p:inputText id="address" value="#{testEntity.address}">
<f:validator validatorId="emailValidator" disabled="#{testEntity.type != 'Email'}"/>
</p:inputText>
<!-- button to call bean method with testEntity as param -->
</h:form>
It is not working the validator is never active but the ajax call is working since I can see the change value in other fields.

That's unfortunately not possible. The <f:xxx> tags are taghandlers (not UI components) which run during view build time, not during view render time. So if it's disabled during building of the view, it'll always be disabled until the view is recreated (e.g. by new request or a non-null navigation).
You'd need to have a "global" validator which delegates further to the desired validator based on the type attribute.
E.g.
<p:inputText ... validator="#{testEntity.validateAddress}" />
with
public void validateAddress(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (type == Email) {
context.getApplication().createValidator("emailValidator").validate(context, component, value);
}
}
Update OmniFaces has recently added a new <o:validator> tag which should solve exactly this problem as follows:
<o:validator validatorId="emailValidator" disabled="#{testEntity.type != 'Email'}"/>
See the showcase example here.

Maybe someone is interested in how I solved it thanks to BalusC help.
Pass type component clientId to custom converter.
<f:attribute name="typeComponentId" value=":formId:type"/>
Validator:
public class TestEntity implements Validator
{
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
final String typeComponentId = (String)component.getAttributes().get("typeComponentId");
final UIInput compType = (UIInput)context.getViewRoot().findComponent(typeComponentId);
if(compType != null)
{
final Type type = (Type)compType.getValue();
if(type == Type.Email)
new EmailValidator().validate(context, component, value);
}
}
}
Edit:
Not working inside a ui:repeat component such as p:datatable.

Related

ClassCastException for <h:selectManyCheckbox> with validation on ajax update when INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL is active

I have a <h:selectManyCheckbox> that has a required-validation on. If I submit the form, I get a validation error when nothing is selected. So far, this ist expected. However, if I do an ajax update on the checkbox then, I get a ClassCastException. But only if empty values are treated as null.
So, I have the following setup. In the web.xml I set
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
Then I have an xhtml-page like this:
<h:form id="main">
<h:selectManyCheckbox id="value" value="#{testcb.selected}" required="true" requiredMessage="Select at least one entry">
<f:selectItems value="#{testcb.available}"/>
</h:selectManyCheckbox>
<div><h:message for="value" style="color:red;"/></div>
<h:outputLabel for="checkit" value="Enter some text: "/>
<h:inputText id="checkit" value="#{testcb.text}">
<f:ajax event="change" execute="#this" render=":main:value"/>
</h:inputText>
<div><h:commandButton type="submit" value="Submit" action="#{testcb.action}"/></div>
</h:form>
And this backing bean:
#Named("testcb")
#SessionScoped
public class TestCBBean implements Serializable {
private final Set<TestValue> available = EnumSet.allOf(TestValue.class);
private final Set<TestValue> selected = EnumSet.noneOf(TestValue.class);
private String text;
public void action() {}
public Set<TestValue> getAvailable() { return available; }
public void setAvailable(Set<TestValue> available) {
this.available.clear();
this.available.addAll(available);
}
public Set<TestValue> getSelected() { return selected; }
public void setSelected(Set<TestValue> selected) {
this.selected.clear();
this.selected.addAll(selected);
}
public String getText() { return text; }
public void setText(String text) { this.text = text; }
}
And this enum:
public enum TestValue { ONE, TWO, THREE }
I am running this in Wildfly 26.0.1-Final (JavaEE 8). But this also happens in older versions (like Wildfly 15). What I am doing:
enter some text and leave the box: an ajax update runs setting the value successfully in the model
I press submit: the validation error for the empty checkboxes pops up
I modify the text in the input and leave the box: the ajax update results in the following Exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to class [Ljava.lang.Object; (java.lang.String and [Ljava.lang.Object; are in module java.base of loader 'bootstrap')
com.sun.jsf-impl#2.3.17.SP01//com.sun.faces.renderkit.html_basic.MenuRenderer.getSubmittedSelectedValues(MenuRenderer.java:508)
com.sun.jsf-impl#2.3.17.SP01//com.sun.faces.renderkit.html_basic.SelectManyCheckboxListRenderer.encodeEnd(SelectManyCheckboxListRenderer.java:89)
javax.faces.api#3.1.0.SP01//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:600)
javax.faces.api#3.1.0.SP01//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
com.sun.jsf-impl#2.3.17.SP01//com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:628)
com.sun.jsf-impl#2.3.17.SP01//com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:159)
javax.faces.api#3.1.0.SP01//javax.faces.component.UIComponent.visitTree(UIComponent.java:1457)
javax.faces.api#3.1.0.SP01//javax.faces.component.UIComponent.visitTree(UIComponent.java:1469)
javax.faces.api#3.1.0.SP01//javax.faces.component.UIForm.visitTree(UIForm.java:355)
On the ajax update the checkboxes are not submitted. But they seem to contain an empty string as submitted value from the validation step before.
When setting the context parameter to false this works. But I want to keep it on true. Any ideas how I could work around this problem?
Reproduced. This is indeed a bug in Mojarra.
It boils down to that the following method in UIInput superclass ...
#Override
public Object getSubmittedValue() {
if (submittedValue == null && !isValid() && considerEmptyStringNull(FacesContext.getCurrentInstance())) {
return "";
} else {
return submittedValue;
}
}
... is not overridden in UISelectMany superclass in such way that it returns new String[0] instead of "". This was an oversight during implementing Faces issue 671.
I have fixed it in Mojarra issue 5081.
In the meanwhile, until you can upgrade to the Mojarra version containing the fix, you can temporarily work around it by copy pasting the entire source code file of UISelectMany into your project while maintaining the package and adding the following method to it:
#Override
public Object getSubmittedValue() {
Object submittedValue = super.getSubmittedValue();
return "".equals(submittedValue) ? new String[0] : submittedValue;
}

JSF Primefaces ajax rendered not updating

I am trying to write a simple create user page. I want the user to be able to type a desired username and if the username is already taken, then an output text shows up and says "Username already in use".
Here is my xhtml page
<tr>
<td>Username: </td>
<td>
<p:inputText id="username" value="#{createUserManagedBean.username}" required="true" requiredMessage="Username is required.">
<p:ajax event="keyup" update="uniqueUsernameMessage"/>
</p:inputText>
</td>
<td>
<h:outputText id="uniqueUsernameMessage" value="Username already in use" rendered="#{!createUserManagedBean.checkUniqueUsername()}" />
</td>
</tr>
Here is my managed bean
public boolean checkUniqueUsername()
{
if(!StringUtils.isBlank(getUsername()))
{
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
boolean result = getUserService().validateUniqueUsername(userDTO);
return result;
}
else
return false;
}
My issue is that the message is not updating for each keyup event. The service was being called, but the element was not changing whether or not it would display or not depending on the method result.
Using the rendered attribute is absolutely not the right way to validate an input component. You should be using a real Validator implementation. Therein you can in case of invalidation just throw a ValidatorException with a FacesMessage. JSF will then take care that the FacesMessage ends up in the right <h:message> associated with the input component.
All in all, this should do:
<p:inputText id="username" value="#{createUserManagedBean.username}" ...>
<f:validator binding="#{uniqueUsernameValidator}" />
<p:ajax event="keyup" update="usernameMessage" />
</p:inputText>
<h:message id="usernameMessage" for="username" />
With
#ManagedBean
#RequestScoped
public class UniqueUsernameValidator implements Validator {
#EJB
private UserService userService;
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null || value.isEmpty()) {
return; // Let required="true" handle.
}
String username = (String) value;
if (userService.findByUsername(username) != null) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Username already in use. Please choose another", null));
}
}
}
See also:
How to perform validation in JSF, how to create a custom validator in JSF
Please note that the validator is a #ManagedBean instead of a #FacesValidator because the #EJB could otherwise not be injected. But if you're not using EJBs and are manually creating service classes and fiddling with transactions yourself, then you could probably just keep it a real #FacesValidator:
#FacesValidator("uniqueUsernameValidator")
public class UniqueUsernameValidator implements Validator {
Which is then instead to be referenced as follows:
<f:validator validatorId="uniqueUsernameValidator" />
See also:
How to inject in #FacesValidator with #EJB, #PersistenceContext, #Inject, #Autowired

custom validator call on button through ajax

hi i wrote a custom a validator which gets the system name and compare it against the id in database, now i wanna apply a check if this value is exactly the same, user must be allowed to click the button and move on else some error message should be displayed. and i am really confused how to call the validator() on through ajax.
my view page code is
<h:commandButton action="sample?faces-redirect=true" value="submit">
<f:ajax execute="#{csample.UserValidator}" render="#form" >
<h:inputText name="idtext" value="#{csampleBean.id}" />
</f:ajax>
</h:commandButton>
and my custom validator
public void UserValidator(FacesContext context, UIComponent toValidate, Object value)
throws UnknownHostException, ValidatorException, SQLException, NamingException
{
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
String machine= localMachine.getHostName();
String query = "select * from USER_ where USER_ID = '"+machine+"'";
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
Statement stat = conn.createStatement();
//get customer data from database
ResultSet result = stat.executeQuery(query);
if (query==machine)
// what to do here
conn.close();
need some guidance
You need to create a class implementing the Validator interface. On validation fail, just throw a ValidatorException with a FacesMessage. JSF will then take care that the FacesMessage ends up in the right <h:message> associated with the input component.
You can register the custom validator to JSF by annotating it with #FacesValidator with therein the validator ID. You can reference it in <h:inputXxx validator> or <f:validator validatorId>.
Here's a kickoff example:
#FacesValidator("userValidator")
public class UserValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// ...
if (!valid) {
String message = "Sorry, validation has failed because [...]. Please try again.";
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
}
}
}
Which is been used as follows (note: <h:inputText> does not have name attribute! instead use id; also note that your initial code snippet has some nesting which isn't making any sense):
<h:inputText id="idtext" value="#{csampleBean.id}" validator="userValidator">
<f:ajax render="idtextMessage" />
</h:inputText>
<h:message id="idtextMessage" for="idtext" />
<h:commandButton action="sample?faces-redirect=true" value="submit" />
See also:
How to perform validation in JSF, how to create a custom validator in JSF
Unrelated to the concrete problem, your JDBC code is leaking DB resources. Please fix that as well.

JSF 2.0; Validator tag "disabled" depends on value from page

In my jsf application i want to validate a field which should only be validated, when one option in a SelectOneRadio is checked.
I found out, that <f:validator> has an attribute, called "disabled".
Can i use this, to check the value from another field?
I tried, but i haven't access to the value from my bean.
<h:selectOneRadio value="#{myBean.checkedSelectOneRadioValue}">
<f:selectItems value="#{myBean.valuesForSelectOneRadio}" />
</h:selectOneRadio>
<f:validator validatorId="myValidator" disabled="#{myBean.checkedSelectOneRadioValue == 'TEST'}" />
Is there any way to reach that without writing own validatorhandler?
Thanks!
The <f:validator> is a tag handler, not an UI component. All its attributes are per definition evaluated during view build time, not during view render time. The view build time is that moment when the XHTML file is been parsed into a JSF component tree as available by context.getViewRoot(). The very same view is usually reused across postbacks to the same view by returning null/void in (ajax) actions.
So you can't let a tag handler attribute depend on a render time attribute which can change during a postback request. One of the ways is to perform that check inside the custom validator itself.
E.g.
<h:inputText>
<f:validator validatorId="myValidator" />
<f:attribute name="radio" value="#{myBean.checkedSelectOneRadioValue}" />
</h:inputText>
with
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (!"TEST".equals(component.getAttributes().get("radio"))) {
return;
}
// Perform actual validation here.
}
You can alternatively also use OmniFaces <o:validator> instead. It extends the standard <f:validator> with request based evaluation of EL in attributes.
<h:inputText>
<o:validator validatorId="myValidator" disabled="#{bean.checkedSelectOneRadioValue == 'TEST'}" />
</h:inputText>
See also the showcase example and the source code from which an extract of relevance is posted below:
#Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
if (!ComponentHandler.isNew(parent)) {
return;
}
final javax.faces.validator.Validator validator = createValidator(context);
final RenderTimeAttributes attributes = collectRenderTimeAttributes(context, validator);
final ValueExpression disabled = getValueExpression(context, "disabled", Boolean.class);
((EditableValueHolder) parent).addValidator(new javax.faces.validator.Validator() {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (disabled == null || Boolean.FALSE.equals(disabled.getValue(context.getELContext()))) {
attributes.invokeSetters(context.getELContext(), validator);
validator.validate(context, component, value);
}
}
});
}
With JSF 2.0 you can use f:ajax for a partial submit. Add this tag to your h:selectOneRadio:
<h:selectOneRadio value="#{myBean.checkedSelectOneRadioValue}">
<f:ajax render="idOfInputText"/>
<f:selectItems value="#{myBean.valuesForSelectOneRadio}" />
</h:selectOneRadio>
...
<h:inputText id="idOfInputText">
<f:validator validatorId="myValidator"
disabled="#{myBean.checkedSelectOneRadioValue eq 'TEST'}" />
</h:inputText>
Replace the renderattribute content with the real id of your input field with the validator. This assumes that the selectOneRadio and the inputText are inside the same NamingContainer.
To avoid extended discussions in comments, i will provide my suggestions as an answer to discuss it further...
At first it should be
disabled="#{myBean.checkedSelectOneRadioValue == 'TEST'}
or
disabled="#{myBean.checkedSelectOneRadioValue eq 'TEST'}
Additional, at least in ICEFaces (and MyFaces should have this function, too), you may use:
<h:selectOneRadio value="#{myBean.checkedSelectOneRadioValue}" partialSubmit="true">
<f:selectItems value="#{myBean.valuesForSelectOneRadio}" />
</h:selectOneRadio>
This should force an ajax request after changing the value of selectoneradio and the validator-disabled check should be able to get it from the bean.
If that does not work, there may be autoSubmit or similar in MyFaces...

jsf custom converter

I'm new to jsf 2.0 and spring 3.0 , i have a requirement to use custom converter in jsf 2.0.But it is not recognized,when i access my xhtml page it is showing an exception
"Named object not found" .I had used #FacesConverter annotation for the custom converter and it is using in the h:selectOneMenu.But i'm getting the error.could any one help in this...
#FacesConverter("selectItemsConverter")
public class SelectItemsConverter implements Converter {
public Object getAsObject(FacesContext context, UIComponent component, String value) {
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
}
}
h:selectOne Menu code is as follows:
<h:selectOneMenu style="width:100px;height:24px;" rendered ="#{row.edit}" value="#{row.modelo.country}" converter="selectItemsConverter" required="true" requiredMessage="#{msg['veci.admin.ccaa.pais.empty']}">
<f:selectItems value="#{communityView.countries}" var="con" itemLabel="#{con.nombrePais}"/>
</h:selectOneMenu>
Thank you to all.............
If you want to call the converter by its converterID you need to change your code as follows:
<h:selectOneMenu style="width:100px;height:24px;"
rendered ="#{row.edit}"
value="#{row.modelo.country}"
required="true"
requiredMessage="#{msg['veci.admin.ccaa.pais.empty']}">
<f:converter converterId="selectItemsConverter"/>
<f:selectItems .../>
</h:selectOneMenu>
The converter attribute of the h:selectOneMenu needs a fully qualified class name such as:
<h:inputText
converter="javax.faces.convert.IntegerConverter" />
If you want to give your converter a custom id use the value parameter:
#FacesConverter(value="selectItemsConverter")

Resources