Basit
Basit

Reputation: 8606

How to change inputText values on focus looses and before sending to server

Hope you all will be fine. The scenerio is I have a form on which there is name inputText field. I want that if user type ' in the name then it is replaced by //. I have made the replace function. But I don't know that how can I do it using ajax. Like if I have input field like this

<h:inputText id="name" value="#{user.name}">
    <f:ajax event="blur" render="nameError name"/>
</h:inputText>
<h:message for="name" id="nameError" style="color: red" />

Now I want that if user types 'Basit'Mahmood'Ahmed' in the name field then on focus looses the value becomes //Basit//Mahmood//Ahmed//. So when user presses on submit button then the //Basit//Mahmood//Ahmed// should be posted to the server, not the 'Basit'Mahmood'Ahmed'.

How can I do it in JSF 2.0?

Upvotes: 2

Views: 354

Answers (1)

BalusC
BalusC

Reputation: 1108632

You need to create a converter.

E.g.

@FacesConverter("userNameConverter")
public class UserNameConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return (String) value;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return (value != null) ? value.replaceAll("'", "//") : null;
    }

}

with

<h:inputText id="name" value="#{user.name}" converter="userNameConverter">

The getAsObject() will run during validations phase and do the desired conversion before the model value is been updated and the view is been re-rendered.

Upvotes: 1

Related Questions