Lukas Novicky
Lukas Novicky

Reputation: 952

JSF how to get in validator information if field is required?

I have problem with h:inputText in my application. Some fields might be required some not, and I want to make a custom validator to all thos field, and cannot find information how to check in validator class is UIComponent is required or no.

this is how the input field code looks like:

<h:inputText styleClass="form-control"
         disabled="#{cc.attrs.bean.disableAnswerPosibility(cc.attrs.answer)}"
         value="#{cc.attrs.freeAnswer}"
         requiredMessage="#{msg.fieldRequired}"
         a:requiredForValidator="#{cc.attrs.question.optional}"
         required="#{cc.attrs.question.optional}">
    <f:validator validatorId="stringValidator"/>
</h:inputText>

As you can see I tried passing this information as a passthrough argument. It's rendered as a true/false on web page, but when I try to get it in validator class, it's an object of some sort, without value displayed in web page source, but with code from .xhtml file.

here is code:

Object temp = uiComponent.getPassThroughAttributes().get("requiredForValidator");

and here is what I got:

enter image description here

I just need value - boolean or String. Any suggestions?

Upvotes: 1

Views: 2059

Answers (1)

Tactical Downvote
Tactical Downvote

Reputation: 2393

In the validate method of your validator you can cast the component to javax.faces.component.UIInput and evaluate its required property like so.

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        UIInput inputComponent = (UIInput) component;
        if(inputComponent.isRequired()){

        }
    } 

This validator obviously only works for UIInput components.

Upvotes: 6

Related Questions