Marcos
Marcos

Reputation: 1265

Submit the value without the mask in PrimeFaces <p:inputMask> component

Is there a way to submit to the model just the raw value without the mask (format) in the PrimeFaces <p:inputMask> component?

I mean, if I have this mask 999.999.999-99 in the mask attribute and the component displays 123.456.789-10 as the value entered by the user, I would like to get in the backing bean property just 12345678910 as the value, not 123.456.789-10.

Upvotes: 1

Views: 1102

Answers (1)

Jasper de Vries
Jasper de Vries

Reputation: 20188

You need to write a converter to convert between the value in you backend and the value you want to use in your UI. For example:

@FacesConverter("myConverter")
public class MyConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        if (string == null || string.isEmpty()) {
            return null;
        }
        return string.replace(".", "").replace("-", "");
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        final String value = (String) o;
        if (value == null || value.length() != 11) {
            return null;
        }
        return value.substring(0, 3) + "."
                + value.substring(3, 6) + "."
                + value.substring(6, 9) + "-"
                + value.substring(9);
    }

}

Which can be used as:

<p:inputMask value="#{testView.string}"
             converter="myConverter"
             mask="999.999.999-99"/>

Upvotes: 2

Related Questions