0

I have an input which is a text field and I want the user to only be able to enter positive and negative numbers into this field. I have found other answers to this however they allow the minus sign to be entered at any point in the string where as I only want the minus sign to be entered at the first position of the string.

I also want the user to be able to use the keyboard arrow keys and any keyboard shortcuts for copying, cutting, pasting and selecting etc.

midda25
  • 152
  • 1
  • 2
  • 12
  • Look into http://stackoverflow.com/questions/13289810/javascript-limit-text-field-to-positive-and-negative-numbers – ajbee Dec 16 '16 at 01:28
  • if you're using only `html5` compliant browsers you can use the `pattern` attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-pattern – haxxxton Dec 16 '16 at 01:30
  • @haxxxton that's fine but I need a pattern to check – midda25 Dec 16 '16 at 01:35
  • @AJB this seems an awfully long winded way to achieve the goal – midda25 Dec 16 '16 at 01:36
  • @midda25, do you allow decimals? – haxxxton Dec 16 '16 at 01:36
  • @haxxxton no decimals – midda25 Dec 16 '16 at 01:38
  • 1
    @midda25, `^\-?[0-9]+$` this patten says the value may begin with a `-` or not, and may contain any count of numbers only. The alternative to a no decimal solution would be to use the `step` attribute to limit input to whole numbers up or down https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-step (if you have a min or max you could all those attributes too) – haxxxton Dec 16 '16 at 01:40
  • @midda25, i should note that this will only restrict the `submission` of the form, not limit the input to only allow those characters to be pressed, if your intention is to ignore user input not matching the pattern you will need to use a JS solution: for example https://jsfiddle.net/2k6d3w5w/ – haxxxton Dec 16 '16 at 01:46
  • @haxxxton that js fiddle isn't working. – midda25 Dec 16 '16 at 01:53
  • @haxxton ignoring user input (keystrokes) is a horrible user experience. Many users will think their keyboards are broken. –  Dec 16 '16 at 03:19

0 Answers0