Seitaridis
Seitaridis

Reputation: 4529

Format message in custom JSF validator

I am implementing a custom validator. The detail for messages in stored in the resources. Here is an example of a message: Value is required for {0}. {0} should contain the label of the component.

@FacesValidator("customValidator")
public class CustomValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (validatorCondition()) {
            String summary = Res.getString("error");
            String detail =  ... format detail here
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail));
        } 
    }
}

How can I format the messaged displayed in the validate method?

Upvotes: 1

Views: 960

Answers (1)

BalusC
BalusC

Reputation: 1108557

Use MessageFormat#format().

String template = "Value is required for {0}.";
String label = component.getAttributes().get("label"); // Don't forget to handle nulls. JSF defaults to client ID.
String message = MessageFormat.format(template, label);
// ...

Upvotes: 1

Related Questions