How to make JSF inputText field upper case on blur

BestPractices picture BestPractices · Jun 13, 2012 · Viewed 26.7k times · Source

I would like to make a JSF inputText field into upper case when the user moves focus away from the field. Would it be best to do this using the f:ajax tag and have the blur event trigger a call to the server to do the uppercasing, or would it be best to do this in JavaScript? What would the reason be not to do this in JavaScript? Is it best to always do these sorts of things using an ajax call to the server side?

Answer

BalusC picture BalusC · Jun 14, 2012

There are indeed 2 ways to salvage this.

  1. Using JavaScript.

    <h:inputText ... onblur="value=value.toUpperCase()" />
    
  2. Using JSF.

    <h:inputText ... converter="toUpperCaseConverter">
        <f:ajax event="blur" render="@this" />
    </h:inputText>
    

    @FacesConverter("toUpperCaseConverter")
    public class ToUpperCaseConverter implements Converter {
    
        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
            return (submittedValue != null) ? submittedValue.toUpperCase() : null;
        }
    
        @Override
        public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
            return (modelValue != null) ? modelValue.toString() : "";
        }
    
    }
    

The JS approach is extremely simple. However, this is tamperable by the enduser as it's performed fully at the client side, under full control of the enduser. The enduser can disable/skip that JS code and/or edit the request parameter before it's actually being sent to the server side. The JSF approach isn't tamperable as this is performed fully at the server side, so this results in a more solid and reliable result.

You have to decide based on those facts which one fits the business requirements the best.