Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f:validateRequiered doesn't work as expected

Tags:

jsf-2

I have just created a NetBeans project with JSF 2.0 and I have a problem with f:validateRequired. The bean

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class TestBean {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String action() {
        return "test";
    }
}

and the page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Test</title>
        <h:outputStylesheet name="css/stylesheet.css" />
    </h:head>
    <h:body>
        <h:form>
            <div id="content">
                Value:
                <h:message for="test" />
                <h:inputText value="#{testBean.value}" id="test">
                    <f:validateRequired />
                </h:inputText>
                <br/>
                <h:commandButton action="#{testBean.action}" value="Action" />
            </div>
        </h:form>
    </h:body>
</html>

seems to be allright, but the h:message isn't there until I supply the requered="true" attribute on the inputText. What I am missing? Why the validation does not occure whithout the requered="true" attribute?

like image 722
Papa Avatar asked Jan 01 '26 00:01

Papa


2 Answers

I figured the answer: fields with empty input are not validated at all by default. If you wish to validate such field you have to set required=true. See UIInput.validateValue() JavaDoc

You can enable the validation of empty fields by setting the javax.faces.VALIDATE_EMPTY_FIELDS context parameter to true. See JavaDoc. After doing that the example above works as expected.

like image 63
Papa Avatar answered Jan 02 '26 13:01

Papa


I know this post is kind of old, but I'm using MyFaces and apparently javax.faces.VALIDATE_EMPTY_FIELDS is set to false by default.

like image 26
Marcelo Avatar answered Jan 02 '26 13:01

Marcelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!