1

I have a text box where I restrict user from typing anything other than numeric values. Only 0-9 allowed using jQuery.

My code:

if (event.which < 46 || event.which > 59)
event.preventDefault();

Now, I want to allow a negative sign (only at beginning) with numeric like (-12,-13). I should restrict these scenarios (--1,-1-,1----). Only valid negative numbers should be allowed.

How can I do this using jQuery?

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
user2067567
  • 3,695
  • 15
  • 49
  • 77
  • See this link :http://stackoverflow.com/questions/4544165/checking-if-value-of-a-textfield-is-integer-in-javascript . they give you methods to check for integers, which a negative number also is. – krishwader May 30 '13 at 13:34

2 Answers2

1

you can use this validator: jquery.numeric

http://www.texotela.co.uk/code/jquery/numeric/

Michael Aguilar
  • 766
  • 8
  • 16
  • 1
    Why use a validator for such a small thing? What if the only thing the code needed to do was check for integers? Won't this be too much of an overhead ? – krishwader May 30 '13 at 13:39
  • But adding a 40k js file for doing one operation. Isn't that bad? `:O` – krishwader May 30 '13 at 13:42
  • @passionateCoder actually is 8kb, this have more validations (like ctrl+v) and even can be used in others sections in webpage. Always depende from user if can be useful – Michael Aguilar May 30 '13 at 13:45
  • `did not know that `. Just read the docs. Nice :-) thanks for the enlightenment – krishwader May 30 '13 at 13:49
1

Have you considered... not using jQuery for everything?

<input type="number" step="1" />

This will allow the user to type anything they want, but supporting browsers (all of them if they're up-to-date) will prevent the form from being submitted if the value is not a valid number.

Unsupporting (out-of-date) browsers will submit the form regardless, but that's fine because 1) You should be validating server-side anyway, and 2) any jQuery solution would fail if the user disables JavaScript, whereas this will work without JS in supporting browsers.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592