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?
Use keyup() method to trigger the keyup event when user releases the key from keyboard. Use toLocaleUpperCase() method to transform the input to uppercase and again set it to the input element.
HTML5 Pattern Validation As an aid to form validation we can use HTML5 input patterns to flag when an input is not valid. In the JavaScript examples, the pattern to enforce only uppercase (assuming a single word - no spaces or punctuation) is: <input ... pattern="[A-Z]*" ...>
There are indeed 2 ways to salvage this.
Using JavaScript.
<h:inputText ... onblur="value=value.toUpperCase()" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With