Rectangle 27 28

You should and can not put JSF tags in the message. Also, JSF's own resource bundle won't be used to resolve localized validation messages. JSR303 bean validation is a completely separate API unrelated to JSF.

To internationalize JSR303 bean validation messages, you need to create a separate ValidationMessages.properties file in the classpath root which can be localized by ValidationMessages_xx_XX.properties files.

ERVNomView=Your message here
{key}
@NotEmpty(message="{ERVNomView}")

java - Localization with bean validation in JSF - Stack Overflow

java jsf-2 localization richfaces bean-validation
Rectangle 27 5

JSF conversion and validation will run first in the order it is been declared on the component, with required first. If any of it fails, then the remnant of JSF validation and all the bean validation is completely skipped, else all of the bean validation is executed.

Hard to answer. It solely depends on the functional requirements and the purpose of the validator and how closely tied the validation is to the model or the view.

If the validation needs to run everytime the model property is set (so, it's closely tied to the model), then bean validation would be preferred. But if validation needs to run only once, e.g. during registration (so, it's closely tied to a specific view), then JSF validation would be preferred.

For example, if you're checking the email syntax pattern, then bean validation would make more sense, e.g.:

@Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Email is not in valid format")
private String email;

If you're checking the email existance against the DB, then a JSF validator would make more sense since you don't want it to unnecessarily be executed on every property set. DB calls are not cheap per se.

Again, this is subjective. See what fits the business requirements the best. Maybe you're required to validate it on every property set, for example.

i need to validate the email in registration and update profile, and i want to validate that the email is valid and doesn't exist in the database, so i think that i have to use both JSF Validator and Bean validation, what do you think ?

Note: why didn't you use @Email from hibernate in above sample, and preferred the regex ?

I prefer to be implementation independent unless not really or easily possible. This way the webapp will still work whenever you deploy to a different container with an other JSR303 implementation than Hibernate. You're of course free to put implementation specific restrictions on your webapp (you're using and targeting Tomcat anyway), but this should properly be documented in the main webapp install/deploy manual for the serveradmins.

i got you, but what do you think about the question in the first comment ?

Sorry, I overlooked that. Well, that are technically two separate validations. As to the responsibility, I'd also go for a JSF validator for the existence and a bean validator for the format. However, it would functionally make more sense if the bean validator is executed first before JSF validator (so, first format and then existence). But you cannot control that. Perhaps you could use <f:validateRegex> instead for the format which is placed before <f:validator> for email existence. Depends on the concrete functional requirements.

Question about using FacesValidator (JSF Validation) and Bean Validati...

validation jsf java-ee jsf-2 bean-validation
Rectangle 27 12

By default, JSF does not validate an empty submitted value if Bean Validation (JSR303) is not available in the environment. This behavior can be controlled with the context parameter javax.faces.VALIDATE_EMPTY_FIELDS.

The default value for javax.faces.VALIDATE_EMPTY_FIELDS is auto, meaning that empty fields are validated if Bean Validation (JSR303) is available in the class path.

If you want to validate empty fields anyway without Bean Validation, then explicitly set the context parameter in your web.xml to true like this:

<context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>true</param-value>
</context-param>

It must be said that you normally use required="true" in case you want to validate an input field as required. You don't need to perform that job in your custom validator then.

<p:inputText ... required="true" requiredMessage="Please enter value" />
<f:validateRequired>
<p:inputText ... requiredMessage="Please enter value">
    <f:validateRequired />
</p:inputText>

Do note that you can safely use multiple validators on the very same input component.

validation - JSF custom validator not invoked when submitted input val...

validation jsf jsf-2
Rectangle 27 11

By default, JSF does not validate an empty submitted value if Bean Validation (JSR303) is not available in the environment. This behavior can be controlled with the context parameter javax.faces.VALIDATE_EMPTY_FIELDS.

The default value for javax.faces.VALIDATE_EMPTY_FIELDS is auto, meaning that empty fields are validated if Bean Validation (JSR303) is available in the class path.

If you want to validate empty fields anyway without Bean Validation, then explicitly set the context parameter in your web.xml to true like this:

<context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>true</param-value>
</context-param>

It must be said that you normally use required="true" in case you want to validate an input field as required. You don't need to perform that job in your custom validator then.

<p:inputText ... required="true" requiredMessage="Please enter value" />
<f:validateRequired>
<p:inputText ... requiredMessage="Please enter value">
    <f:validateRequired />
</p:inputText>

Do note that you can safely use multiple validators on the very same input component.

validation - JSF custom validator not invoked when submitted input val...

validation jsf jsf-2
Rectangle 27 5

If you use MyFaces and the bean validation framework (JSR303) try to define a MessageBundle with a key javax.faces.validator.BeanValidator.MESSAGE

<application>
    <message-bundle>ApplicationMessages</message-bundle>
</application>
#javax.faces.validator.BeanValidator.MESSAGE={1}: {0}
javax.faces.validator.BeanValidator.MESSAGE={0}

This defeats the OP's requirement of displaying the input field ID/label in the message.

validation - Why the form id prefix in the h:message output? - Stack O...

forms validation jsf messages prefix
Rectangle 27 1

Looks like your inputText tag is missing the value attribute. The value attribute does the binding between the input and the bean.

<h:inputText value="#{yourBean.yourValue" ...

Hello Christophe, i already tested that before posting. I even did the following <h:inputText value="..." /> without EL. But the error remains. And even worse, i loose the benefit of the html5 attribute "placeholder" which is no longer used if ever i set a default value. Anyway, setting "value" attribute did not do the job.

Concerning HTML5 support you will need to wait for the JSF 2.2 or use OmniFaces if you do not want to wait. Another solution is to add the placeholder via JavaScript once the page has loaded.

As you can see in my screenshot, the placeholder is already currently working. Indeed, i'm using OmniFaces.

Your answer is ok. Actually, before asking my question, i tested the value attribute with a dummy text like this <h:inputText value="..." /> and the error remained. So i thought that the error was not due to the fact that the value attribute was not used. And now i tested with a real bean like this <h:inputText value="#{cc.attrs.value}" /> where value is declared in the <composite-interface> and now the error is gone. I did not realize that i could not use a static string instead, thanks.

forms - JSF 2 - composite-component - Bean validation fails due to com...

forms jsf-2 bean-validation composite-component
Rectangle 27 19

You could do so. It's technically possible. But it does (design)functionally not make any sense. You're basically tight-coupling the model with the controller. Usually the JPA entity (model) is a property of a JSF managed bean (controller). This keeps the code DRY. You don't want to duplicate the same properties over all place, let alone annotations on those such as bean validation constraints.

@ManagedBean
@ViewScoped
public class Register {

    private User user;

    @EJB
    private UserService service;

    @PostConstruct
    public void init() { 
        user = new User();
    }

    public void submit() {
        service.create(user);
    }

    public User getUser() {
        return user;
    }

}
<h:form>
    <h:inputText value="#{register.user.email}" />
    <h:inputSecret value="#{register.user.password}" />
    <h:inputText value="#{register.user.firstname}" />
    <h:inputText value="#{register.user.lastname}" />
    ...
    <h:commandButton value="Register" action="#{register.submit}" />
</h:form>

Thanks for the answer. I want to have a good design. Is your answer a sample of a good design or answer to my question or both? Which design would you suggest for a JSF JPA project as a GURU.:-)

JPA Entity as JSF Bean? - Stack Overflow

jsf entity backing-beans
Rectangle 27 1

For those of you having the same problem as me (the solution given by @BalusC wasn't working with many different properties files for many languages), the thing to do is to name all of the properties files in the following pattern: ValidationMessages_xx.properties

I don't know why, but the pattern ...xx_XX... wasn't working for me.

The pattern xx_XX is for region specific locales, e.g. British English is en_UK, whereas en just stand for English in general. You should always have the general variant to fall back to, then it will work.

java - Localization with bean validation in JSF - Stack Overflow

java jsf-2 localization richfaces bean-validation
Rectangle 27 1

Tried that and it doesn't work, the spec of bean validation says META-INF/validation.xml

@OmarAlKababji Yes the specifications say that, but for me it did not work as well. I had to put it into my WEB-INF/ directory, but I can't really explane why. Try to remove your validation-api-1.0.0.GA.jar from the classpath, maybe you have conflicts in your application.

That does not work with me either, what version of tomcat, jsf, are you using? where are you putting the mapping file?

I am working with JSF 2.0 on a WAS 8. All my configuration files are in WEB-INF, and so can be found in the classes/ folder since it's in the classpath. I guess your application were looking for a META-INF/validation.xml in your classpath, maybe because there's a configuration somewhere that specify that.

having files in the WEB-INF directory does not mean that you get them in the WEB-INF/classes directory in runtime (at least in eclipse). In the java class org.hibernate.validator.xml.ValidationXmlParser there is a constant variable named: VALIDATION_XML_FILE = "META-INF/validation.xml"; so it seems for me that this file should be under META-INF somehow.

jsf 2 - bean-validation validation.xml ignored - Stack Overflow

jsf-2 bean-validation
Rectangle 27 5

Of course that sometimes you cannot only count on Validators but need to do some validation in bean. (most of the times you need this kind of validation when you are validating data for multiple inputs together)

For this case, if you have an h:messages control on the page, this will show the error there:

FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage("This username already exists!"));

If you want to display validation messages per components and not using a general one per page, see this answer.

Ps: Pay attention that if you use h:messages it will also display other components validation messages also. If you do not want this set globalOnly="true"

validation - JSF throw FacesMessage from regular bean method - Stack O...

validation jsf message
Rectangle 27 5

Of course that sometimes you cannot only count on Validators but need to do some validation in bean. (most of the times you need this kind of validation when you are validating data for multiple inputs together)

For this case, if you have an h:messages control on the page, this will show the error there:

FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage("This username already exists!"));

If you want to display validation messages per components and not using a general one per page, see this answer.

Ps: Pay attention that if you use h:messages it will also display other components validation messages also. If you do not want this set globalOnly="true"

validation - JSF throw FacesMessage from regular bean method - Stack O...

validation jsf message
Rectangle 27 9

Either use <h:message> which you attach to specific components by for attribute which should refer the id of the input component:

<h:inputText id="name" value="#{contact.client.name}"></h:inputText>Name (Required)
<h:message for="name" />
<h:inputText id="email" value="#{contact.client.email}"></h:inputText>E-Mail (Required)
<h:message for="email" />
<h:inputText id="website" value="#{contact.client.website}"></h:inputText>Website (Optional)
<h:message for="website" />
<h:inputText id="text" value="#{contact.client.text}"></h:inputText>Message (Required):
<h:message for="text" />

or use <h:messages/> to display them all at a single place:

<h:messages />

Yes, bean validation messages also ends in there.

Don't forget to ensure that the button's render attribute covers them as well.

i follow your tutorial but i have a weird problem, i update my post, please coud you take a look ?

Is the concrete problem solved? Your new problem is unrelated. It look more like just a CSS issue.

yeah it is mate, thanks by the help. i will take a look in my CSS though.

It mentions it in your tutorial but javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL needs to be set as a context-param in the web.xml for the @NotNull bean validator to work properly. Just for anyone wondering why your bean validation messages aren't appearing (like I was)

java - JSF: How validate fields and return error messages by bean vali...

java jsf jsf-2 bean-validation
Rectangle 27 11

You've not declared the bean using @SessionScoped from javax.faces.bean package, but instead from javax.enterprise.context package. This don't work in combination with @ManagedBean from javax.faces.bean package. The bean will then default to the request scope and behave like @RequestScoped.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class ProjectCurrentBean implements Serializable {

omg, thank you! what a mistake

Be careful with IDE autocomplete.

jsf - JSF2 Can't reach SessionScoped bean from ViewScoped as ManagedPr...

jsf jsf-2
Rectangle 27 2

I'm guessing you have a bean that looks something like this...

public class SomeBean {
   boolean selected = false;
   String someProperty;

   ...
}

If you have a controller for those beans your markup would look something like this...

<h:dataTable value="#{SomeController.someBeans}" var="someBean">
   <h:column> 
      <f:facet name="header">Select</f:facet>
      <h:selectBooleanCheckbox value="#{someBean.selected}"/>
   </h:column>
   <h:column> 
      <f:facet name="header">Input</f:facet>
      <h:inputText value="#{someBean.someproperty}" required="#{someBean.selected}"/>
   </h:column>
</h:dataTable>

Validation for selected row in JSF h:datatable - Stack Overflow

validation jsf datatable
Rectangle 27 4

javax.faces.validator.BeanValidator
input.addValidator(new BeanValidator());

The reason is that default validators (BeanValidator is registered as one) are added during tag execution: http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-635.

java - JSF 2 dynamic form and bean validation JSR 303 - Stack Overflow

java jsf jsf-2 bean-validation dynamic-forms
Rectangle 27 3

i8taken solution converts number into long without validation message (at least in my case: JSF2 / global messages per page). For proper validation message you can 1. check value in action method in bean; or 2. use converter attribute for inputText:

<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" maxlength="4" converter="javax.faces.Integer" />

JSF Number Validation - Stack Overflow

jsf
Rectangle 27 2

The problem is, that actually the bean does not hold the selected value because of readonly="true". When you apply that property to an UIInput the UIInput will not be processed on a submit.

readonly="#{facesContext.renderResponse}"
isReadonly
readonly="#{myView.isReadonly}"
public boolean isReadonly() {
    return FacesContext.getCurrentInstance().getRenderResponse();
}

Form validation clears JavaScript field - Stack Overflow

javascript validation jsf seam
Rectangle 27 2

Put the bean with request scoped data in request scope, not in session scope.

You probably have the entire list in session to "save" DB calls and all the work to retain values in the subsequent requests inside the same session. You can use a separate session scoped bean for that, e.g. DataManager. Then you should have a request scoped bean to represent the selected item, e.g. DataItem. You can familarize the both beans with help of managed property injection.

You're right BalusC, I've my bean in session because I'm waiting for the Cobol service layer. I didn't think that could be the cause. I'll confirm this theory as soon as I come back at work, in 2010. Thanks for your help.

validation - JSF - force UIInput components to refresh - Stack Overflo...

validation jsf refresh lifecycle
Rectangle 27 2

You should include a validation method or validator for the inputText component so as to reverse the bean value and prevent execution of the onSave event when the given ID already exists in the database.

Knowingly attempting to insert a record into a database hoping for database constraints to provide validation is a nebulous data security practice. I am not saying that database constraints are bad, I am just saying that you should make every attempt to validate and santize your inputs before attempting to insert into the database.

Include a validation method in your managed bean like such:

public void validateStaffNoId(FacesContext context, UIComponent component, Object value)
        throws ValidatorException {
    //Query DB to see if ID exists...
    if (idExists()) {
        //Throw validator exception
    }
}

Then in your inputText component simply add the attribute:

<p:inputText ... validator="#{staffBean.validateStaffNoId}" ... />

I had hoped to avoid this because this means I have to do an additional DB-query just to verify the existence of an entity. Is there any other way? Can I reverse the bean in some other way? Why is it bad to rely on constraint exceptions?

is it bad to rely on constraint exceptions?

@javaMS In the case of JSF, there is the Validation phase where the entire framework will handle applying and rolling back values based on Application Validation. JSF encourages this model so it is best to do it this way regardless of your feelings on the subject. Another point is that some databases perform worse by enforcing referential integrity than by fetching a single record. The performance loss of pre-fetching this record should be minimal if the table is properly indexed.

I fully buy what you are saying but I still dont like the design with two queries when I can have it solved using one. Your second point is convincing. However, in order to comply with the framework, can I manually fail the validation in my exception handling? I tried using FacesContext.getCurrentInstance().validationFailed(); FacesContext.getCurrentInstance().renderResponse(); but it only does half the job, i.e. leaves the field in editable mode and provides me with the error message. It does not allow any further action and cancel button doesn't work.

There is actually another reason for why catching the Exception might be preferable: concurrency. In case of two clients, C1 and C2 trying to write to DB, if I merely rely on application code then it might be that the first query (check query) applied when C1 was trying to write will return "no records found", but C2 writes immediately after that check but before C1 has managed to write to the DB.

java - Resetting value of p:inputText in p:inplace when DB constraint ...

java jsf primefaces
Rectangle 27 3

Your concrete problem is caused because you aren't starting the conversation in @PostConstruct and thus the bean behaves like request scoped. This way the list of cities will incompatibly change during processing the form submit and become empty (and thus the selected item couldn't be found in the list of available items and hence this validation error).

You need to start the conversation in the @PostConstruct.

conversation.begin();

Unrelated to the concrete problem, using valueChangeListener and performing business logic in getter methods is the wrong approach. You should not be performing business logic in getter methods at all. This is plain inefficient. They should solely return already-prepared bean properties.

Rewrite your logic as follows:

<p:selectOneMenu value="#{bean.country}" ...>
    <f:selectItems value="#{bean.countries}" />
    <p:ajax listener="#{bean.updateCities}" update="city" />
</p:selectOneMenu>

<p:selectOneMenu id="city" value="#{bean.city}" ...>                                         
    <f:selectItems value="#{bean.cities}" />
</p:selectOneMenu>

with

private Country country;
private List<Country> countries;
private City city;
private List<City> cities;

@PostConstruct
public void init() {
    countries = service.listCountries();

public void updateCities() {
    cities = service.listCities(country);
}

// Add/generate normal!! getters/setters.
selectOneMenu

Still the Java EE prophet saves us from darkness :). Totally forgot about beginning the conversation. I was willing to move logic from getters onto proper logic methods as a final refactoring for the bean but I wanted to spot the issue behind the value validation error first. Thanks a Lot Sir b.Scholtz. It's all working fine now.

ajax - Populating a chlid jSF selectOneMenu - implicit value validatio...

ajax jsf java-ee primefaces selectonemenu