jQuery code to allow numbers, alphabets or specific characters

There is a general requirement in many projects where for certain fields or input only numeric, alphabets, specific character or set of characters must be allowed. For example, When you are requesting input for Phone number or Zip code from the end-user, then you don't want to allow user to enter any alphabets.

There are plenty of jQuery plugins available that satisfy your requirement where you want to restrict user to enter only numbers.

Many times, we write lots of code to achieve such functionality. But we live in an era where plenty of plugins are available then why to rewrite where same thing already exists. That's why there are plugins. I always believe it is a better choice to use existing code or plugin rather than coding it again.

While searching, I found a jQuery plugin called "AlphaNumeric" and it really caught my attention as I found this very useful.

The beauty of this plugin is that it has some standard methods that allows only numeric, alphabets and alphanumeric character but other than that you can also set which other characters you want to allow. As for example, for phone number, other than 0-9 you also want to allow user to enter "-" or space. You can set this very easily.

This plugin has 3 standard methods.
1. numeric : Allows only numeric characters.
2. alpha : Allows only alphabets
3. alphanumeric : Allow alphabets and numeric characters.

Other than these standard methods, this plugin comes with properties.
1. allow : Specify which other characters you want to allow.
2. ichras : Specify characters that needs to be prevented.
3. allcaps : Only uppercase characters are allowed.
4. nocaps : Only lowercaps characters are allowed.

Code Samples:

To allow only numbers:

$('#txtNum').numeric();

To allow only alphabets:

$('#txtAlpha').alpha();

To allow only numbers and alphabets:

$('#txtNum').alphanumeric();

Allow only numeric characters, and some other characters like dot,comma (.,)

$('#txtNum').numeric({allow:".,");

Also read my other post, which describe how to allow arrow keys with number.

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...