0

I have an <h:inputText> tag, and I only want to allow numbers to be entered with no more than 1 decimal.

This allows only numbers, but I cannot get it to allow only 1 decimal.

<h:inputText value="#{bean.someNumber}"
  size="6" styleClass="some-style"
  onkeypress="if(event.which &lt; 48 || event.which &gt; 57) return false;"
  pt:placeholder="0.0">
</h:inputText>

I tried adding (event.which == 190) to the onkeypress attribute, but I can't get it to work. (190 is the . key)

Note: This is trying to restrict what the user can enter into the input field, not validating server side, that already works.

Any help would be appreciated.


Update I tried to change the onkeypress with pt:oninput like the code below. It only allows digits and 1 decimal place, but it does not allow a - sign as the first character for negative numbers.

pt:oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"

Alex
  • 160
  • 1
  • 2
  • 22
  • 1
    Possible duplicate of [Restricting input to textbox: allowing only numbers and decimal point](https://stackoverflow.com/questions/2808184/restricting-input-to-textbox-allowing-only-numbers-and-decimal-point) – Selaron Oct 02 '19 at 19:56
  • 1
    Bewhare that you should bind the inout value to a decimal typed bean property and/or you should add a validator in order to securely restrict input server side. – Selaron Oct 02 '19 at 19:59
  • 1
    Ever thought of using a `mask` look at [this](https://www.primefaces.org/showcase/ui/input/inputMask.xhtml). I hope it helps you – fuggerjaki61 Oct 03 '19 at 17:17
  • @fuggerjaki61 that helps a lot. Much better solution. – Alex Oct 03 '19 at 17:51

0 Answers0