This post shows you how to restrict typing special characters in a text box using jQuery and regular expression.
This script not only restricts typing special characters but also restricts pasting into the text box.
Here is the regular expression for removing and finding special characters in a string.
1 2 |
/*javascript regex for finding special characters*/ /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi |
In this regular expression all special characters are included, if you feel you don’t want to restrict specific characters then you can delete it from that, especially dot and comma.
And here it the entire example script for you to play around with it,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function(){ $('#txt_box').keyup(function() { var yourInput = $(this).val(); re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi; var isSplChar = re.test(yourInput); if(isSplChar) { var no_spl_char = yourInput.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''); $(this).val(no_spl_char); } }); }); </script> </head> <body> <h3>Restrict Special Characters in textbox with JavaScript - <a href="http://www.tutorialsmade.com">Tutorialsmade.com</a></h3> <h4>Try to type Special Characters in this text box</h4> Your Input: <input type="text" id="txt_box" value="" /> </body> </html> |
Demo to test it:
This was helpful.. Thank You 🙂
Works like a charm 🙂 Thanks a lot 🙂
This helped me a lot thank you.
super g
it is working amazing …
Thanks, this is working fine….
But it allows special character if i paste them from clipboard using right click and paste.
hi,
I need an event like input box which allows special characters, numbers, all the things.. but not allow only special characters or only numbers…
can you help on this
Thanks, this is working fine….Good
This is very nice code. Thanks
its working good
Thank You ! You are treat to my headache.
working fine.
Thank You. Solved my issue.
Thank you so much…its working fine…
Thank you. You solved my problem.
Hi this is awesome article. Thanks for sharing this with us. really helpful. keep it up.