Reputation: 71
I have a input text where is should restrict user from entering negative symbol to be entered only at the starting of string.
Since I am using a custom primefaces jar, I am not able to use p:inputNumber
(By mapping bigdecimal). OnKeyPress
event I have added to allow numbers and DOT symbol. But I couldn't restrict the user from entering negative symbol inside the string. Is there any way I could achieve it in onkeypress
event. I have given my code below
<h:inputText value="#{dimStackLine.max}"
onkeypress="if( (event.which < 48 || event.which > 57) && event.which != 46 ) return false;">
<p:ajax event="change" process="@this"></p:ajax>
<f:convertNumber pattern="####0.00000" />
</h:inputText>
Upvotes: 2
Views: 800
Reputation: 2321
Just add an exception for the first character entered. You can do this by doing something like this;
<h:inputText value="#{downloadBackingBean.value}" onkeypress="if(($(this).val().length == 0 && even.which == 45) || ((event.which < 48 || event.which > 57) && event.which != 46 )) return false;">
<p:ajax event="change" process="@this"></p:ajax>
<f:convertNumber pattern="####0.00000" />
</h:inputText>
As you can see this just adds an extra check - allowing you to enter the minus sign if its the first character in the inputfield.
If you go this route, make sure you validate the value before it populates your backing bean.
Another way is to do this server side. You can push the value up to the backing bean via a valueChangeListener. You can then ajaxify the process and revert to server side validation by doing something like this,
<h:form>
<h:inputText valueChangeListener="#{bean.onNewValue}" value="#{bean.value}">
<f:ajax event="keyup" render="@form" execute="@form"/>
</h:inputText>
</h:form>
The valueChangeListener is called prior to the backing bean value being set. This allows you to continuously check the incoming values and handle them accordingly. Like stripping unwanted characters.
You should easily be able to combine this with either bean validation or JSF validation depending on what your environment supports.
Upvotes: 2