Reputation: 515
In my XHTML page I have some inputText fields where the user can insert numeric values in the format "999,999" (max three integer values, max three decimal values). The decimal separator is ",", because I want to format the above fields using the Italian locale.
Actually this is my p:inputText component:
<p:inputText value="#{r.value}" id="verog_#{r.id}"
onkeypress="return isNumberKey(event)" />
The isNumberKey() javascript function enables permitted characters only (numbers and comma):
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 44) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
But I have no control on the maximum number of digits allowed, so the user can, for example, input a number like "1234,5678", or, even worse, "12,,34".
I need to check these values on the client side because they are within a dialog. Actually I make checks on the server side, after the "save" button is clicked:
<p:commandButton value="save" action="#{myBean.saveAction}" ajax="true"
update=":growl" oncomplete="dialogVar.hide()">
<f:param name="action" value="#{action}" />
</p:commandButton>
But if I have an input error, the dialog is always hidden, and the user is forced to submit the values again.
I cannot use f:convertNumber, because data are saved on the db as strings, not as numbers.
I also tried to use the p:inputMask component, but I cannot make it to work properly (maybe for a lack of knowledge): the mask "999?,999" does not fit my requirements.
Maybe I can do it using a converter (the p:inputText component has the "converter" and "converterMessage" attributes), but my converter attempts failed too:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALIAN);
nf.setMaximumIntegerDigits(3);
nf.setMaximumFractionDigits(3);
String result = nf.format(submittedValue);
It always gives me IllegalArgumentException, even if submittedValue is 0.
How can I reach my goal? Thanks in advance.
Upvotes: 1
Views: 2438
Reputation: 22847
You need to test the whole value on the client side.
I've made a fiddle with example JS validation: http://jsfiddle.net/lechlukasz/w8K8j/1/
It calls validation function on blur:
function valid(val) {
var reg = new RegExp('^[0-9]{1,3}(,[0-9]{1,3})?$');
if (!reg.test(val))
return false;
return true;
}
If you want to make full validation on keypress, don't forget to allow the coma as the last character (illegal in final string, but necessary when typing :)
Upvotes: 0