How do I block special characters from being typed into an input field with jquery?
-
1Use a [jQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) plugin, and allow only alphanumerical characters. – Tomas Aschan May 21 '09 at 22:59
26 Answers
A simple example using a regular expression which you could change to allow/disallow whatever you like.
$('input').on('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
-
62This doesn't work for pasted text & may also prevent the user from non-text keypresses like backspace, arrow keys, etc. – bendytree Jul 02 '12 at 17:41
-
12
-
1Does not work for spanish words like: avión (plane), árbol (tree), etc. – nikoskip Jan 20 '15 at 18:31
-
1
-
3This solution works for me on a Bootstrap-TagsInput element. To address the paste issue, you can simply add "paste" to the event parameter list like so: $('input').on('keypress, paste'', ()=>........ – Jim22150 Jul 10 '20 at 13:50
-
1copying and pasting text with invalid characters will not be handled with this solution but typing key by key works – pixel May 13 '21 at 16:05
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input
event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
-
2+1 I was scrolling down the answers looking for an answer like this one or I would submit my own answer. This answer filters out any disallowed characters instantly! Great! – Emil Hemdal Mar 23 '13 at 13:39
-
3+1 Works for pasted text, doesn't interfere with FF's backspace and delete keys, and doesn't rely on `event.which` or `event.keycode`! Wish I could +10! – rinogo Aug 08 '13 at 18:39
-
4...BUT in Chrome and IE, when you type new characters or use the backspace and delete keys *in the middle of the input text*, the cursor is moved to the end of the text... :/ Is there an easy workaround for this? I wanted so badly for this to work! – rinogo Aug 08 '13 at 18:57
-
So close... this code has very weird behavior in Chrome Mobile. Cursor jumps around on first letter typed and on backspace too. – Juliano Mar 19 '15 at 20:18
-
2@Juliano Interesting, it seems that selectionStart always returns 0 on Chrome Mobile regardless of where the cursor/caret is currently positioned. I'm not sure (yet) if this is a bug or intended behavior. I'm currently researching the issue and will update my answer or comment here when I learn more. – rexmac Mar 19 '15 at 23:23
-
-
This works best for me to only allow alpha or numeric characters. – IlludiumPu36 Nov 22 '19 at 07:38
Short answer: prevent the 'keypress' event:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
Long answer: Use a plugin like jquery.alphanum
There are several things to consider when picking a solution:
- Pasted text
- Control characters like backspace or F5 may be prevented by the above code.
- é, í, ä etc
- Arabic or Chinese...
- Cross Browser compatibility
I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:
$("input").alphanum();
Or for more fine-grained control, add some settings:
$("#username").alphanum({
allow : "€$£",
disallow : "xyz",
allowUpper : false
});
Hope it helps.

- 3,195
- 4
- 22
- 26
-
1Awesome stuff man, awesome. I just had to add an option for enabling/disabling the slash char ('/') as it did not work while putting it in the `allow` setting. But that's the beauty of jquery plugins, the fact that you can modify them to suit your needs. Thanks! – Adrian Marinica May 10 '13 at 11:37
-
Thanks Adrian. Btw, I just tried enabling the slash using the `allow` option and it worked ok for me using this code: `$('#firstName').alphanum({allow: "/"});` Any chance you could provide more info? If there is a bug or a problem with the docs it would be nice to get it fixed. Cheers – KevSheedy May 10 '13 at 14:51
-
Hi KevSheedy, thanks for taking the time to test this out. Sorry I did not make it clear enough. The problem was that I also had `allowOtherCharSets: false` and `allowCaseless: false`. These interfered with the settings set in `allow`. From my point of view, I think that the `allow` option should veto out all the other options (like `allowOtherCharSets` or `allowCaseless`). So if you specify a character in the `allow` option, it should be allowed regardless of the other options set in the configuration object. Same goes for `disallow`. But this is just my opinion. :) Cheers again! :) – Adrian Marinica May 13 '13 at 06:19
-
Good point Adrian. I've gone ahead and published a fix in V1.0.6 to make `allow` and `disallow` have a higher priority. It's logged in [issue #7](https://github.com/KevinSheedy/jquery.alphanum/issues/7). Hope it helps – KevSheedy May 13 '13 at 09:26
-
8
-
This is great! The only catch is - no license is there on github :( certain projects prevent the use of the plugins which license status is unknown. – zaitsman Nov 10 '13 at 06:58
-
I saw no explanation on how this handles characters for different languages. Could you elaborate on if it allows characters like é, í, ä, Arabic, or Chinese characters? – Crystal Miller Aug 21 '14 at 17:52
-
I really like this and so i tried it out with a phonegap app im making. used your basic example disallowing xyz. and at first when you press them they appear and then disappear (like a flicker). which was fine but when i pressed the x key a third time it appeared and stayed there. maybe there's something incompatible in phonegap? – Sarah Sep 11 '16 at 14:10
-
2Everyone seems pretty thrilled with this but a user can easy paste text with any characters and this won't prevent that. – Jonathan Wood Mar 24 '17 at 14:16
Use simple onkeypress event inline.
<input type="text" name="count" onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">

- 331
- 3
- 4
Use HTML5's pattern input attribute!
<input type="text" pattern="^[a-zA-Z0-9]+$" />

- 547
- 5
- 15
-
29While this solution prevents undesired characters from being submitted, it _does not_ prevent undesired characters from being entered into the input field. – rexmac Mar 19 '15 at 23:36
-
4There is also the risk that the user is not using an HTML5 browser. – Captain Kenpachi Aug 11 '16 at 08:58
-
3From UX experience, one thing many people hate more than being restricted in what they can type is being told you did it wrong afterwards. - Forcing of input is to reduce error messages and invalid notifications. – Julix Oct 14 '16 at 02:15
-
2@Julix Its a case by case thing. There are some fields that can only be numeric (price or any currency amount, etc) where it doesn't make sense to listen to alphabetic character input. But yeah mine was not really a solution to OP's problem but a nice and easy way to help with the UX problem. – keepitreal Apr 23 '17 at 23:54
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});

- 32,158
- 14
- 82
- 96

- 560
- 3
- 16
-
This should be the most upvoted answer. Most of the answer don't take into account those special characters that doesn't have an associated value. – Alain Cruz Sep 19 '20 at 20:06
-
-
this works great but you can still copy and paste invalid characters in the input field – pixel May 13 '21 at 16:31
Your textbox:
<input type="text" id="name">
Your javascript:
$("#name").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

- 1,134
- 1
- 17
- 33
-
@Bhargav Rao, I deleted the other duplicate post and reposted this one because this one was more appropriate, thanks for pointing that out – chandler Jul 10 '17 at 15:47
-
2This will not work when copying and pasting text with invalid characters though – pixel May 14 '21 at 15:19
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});

- 50,140
- 28
- 121
- 140

- 26,821
- 23
- 116
- 160
-
Is there one for letters? Normally I just use nan for numbers only (like a zip code or phone) – Jan 24 '19 at 17:23
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})

- 51
- 1
- 1
-
why `!e.charCode ? e.which : e.charCode` and not simply `e.charCode ? e.charCode : e.which` ? – Massimiliano Kraus May 04 '18 at 12:32
-
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});

- 154
- 2
- 6
this is an example that prevent the user from typing the character "a"
$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
return false;
});
});
key codes refrence here:
http://www.expandinghead.net/keycode.html
-
I would think that all of the keycodes that you do not want to allow can be overwhelming to try and manage. – RSolberg May 21 '09 at 23:14
-
If you want to restrict someone to only be able to enter numbers 1 through 5, you end up managing 5 keycodes within your code. – RSolberg May 21 '09 at 23:19
-
2It's actually not a bad plan if AlphaNumeric isn't the plugin for you. I made it work with a switch/case statement. This example disallows characters that aren't allowed in directory names: $('input[type='text'], textarea').keydown(function(ev){ switch(ev.keyCode){case 47: case 92: case 63: case 37: case 42: case 59: case 124: case 34: case 60: case 62: return false;}; }); – M Miller Jul 24 '11 at 19:42
-
1@user434917, your code is not working when i test it with android mobile chrome browser. do you have any solution for it..? – Pranesh Janarthanan Feb 22 '19 at 14:43
Write some javascript code on onkeypress event of textbox. as per requirement allow and restrict character in your textbox
function isNumberKeyWithStar(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
return false;
return true;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isNumberKeyForAmount(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}

- 170,088
- 45
- 397
- 571

- 313
- 3
- 11
-
1This is working if I type manually. But I am able to paste copied special characters. – Sunil Garg Jan 06 '16 at 12:30
To replace special characters, space and convert to lower case
$(document).ready(function (){
$(document).on("keyup", "#Id", function () {
$("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
});
});

- 132,869
- 46
- 340
- 423

- 1,267
- 15
- 20
-
This is the perfect answer that everybody should know about it. It passed the copy pasted as well and every special characters. Great job . Thanks – Md. Amanur Rahman Jun 29 '21 at 10:52
You don't need jQuery for this action
You can achieve this using plain JavaScript, You can put this in the onKeyUp
event.
Restrict - Special Characters
e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()
Accept - Number only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
Accept - Small Alphabet only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
I could write for some more scenarios but I have to maintain the specific answer.
Note It will work with jquery, react, angular, and so on.

- 2,490
- 26
- 32
-
Either I am blind or I am missing something, but your second and third option are exactly the same, are they not? – andylib93 Oct 01 '22 at 20:35
just the numbers:
$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=57) { return true; } else { return false; } });
or for time including ":"
$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=58) { return true; } else { return false; } });
also including delete and backspace:
$('input.time').keydown(function(e) { if((e.keyCode>=46 && e.keyCode<=58) || e.keyCode==8) { return true; } else { return false; } });
unfortuneatly not getting it to work on a iMAC

- 1,499
- 12
- 12
Wanted to comment on Alex's comment to Dale's answer. Not possible (first need how much "rep"? That wont happen very soon.. strange system.) So as an answer:
Backspace can be added by adding \b to the regex definition like this: [a-zA-Z0-9\b]. Or you simply allow the whole Latin range, including more or less anything "non exotic" characters (also control chars like backspace): ^[\u0000-\u024F\u20AC]+$
Only real unicode char outside latin there is the euro sign (20ac), add whatever you may need else.
To also handle input entered via copy&paste, simply also bind to the "change" event and check the input there too - deleting it or striping it / giving an error message like "not supported characters"..
if (!regex.test($j(this).val())) {
alert('your input contained not supported characters');
$j(this).val('');
return false;
}

- 179
- 1
- 5
Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
some_element.bind("keypress", function(event) {
// prevent if in array
if($.inArray(event.which,specialChars) != -1) {
event.preventDefault();
}
});
In Angular, I needed a proper currency format in my textfield. My solution:
var angularApp = angular.module('Application', []);
...
// new angular directive
angularApp.directive('onlyNum', function() {
return function( scope, element, attrs) {
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
// prevent these special characters
element.bind("keypress", function(event) {
if($.inArray(event.which,specialChars) != -1) {
prevent( scope, event, attrs)
}
});
var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
,57,96,97,98,99,100,101,102,103,104,105,110,190];
element.bind("keydown", function(event) {
if($.inArray(event.which,allowableKeys) == -1) {
prevent( scope, event, attrs)
}
});
};
})
// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
In the html add the directive
<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">
and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'
...
this.updateRequest = function() {
amount = $scope.amount;
if (amount != undefined) {
document.getElementById('spcf').onkeypress = function (e) {
// only allow one period in currency
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
// Remove "." When Last Character and round the number on blur
$("#amount").on("blur", function() {
if (this.value.charAt(this.value.length-1) == ".") {
this.value.replace(".","");
$("#amount").val(this.value);
}
var num = parseFloat(this.value);
// check for 'NaN' if its safe continue
if (!isNaN(num)) {
var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
$("#amount").val(num);
}
});
this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}
...

- 159
- 3
- 12
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if( $(this).val().indexOf('.') == 0){
$(this).val("");
}
//this is the simplest way
indexof is used to validate if the input started with "."

- 328
- 3
- 10
-
I'm not sure this really adds anything to the (many) existing answers using basically the same approach. – DBS Sep 07 '21 at 12:26
-
The question doesn't say anything about an "add more" text box or any form of invoicing? – DBS Sep 07 '21 at 12:34
Yes you can do by using jQuery as:
<script>
$(document).ready(function()
{
$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='empty') // if username is empty
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='invalid') // if special characters used in username
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='no') // if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>
and script for your user_availability.php will be:
<?php
include'includes/config.php';
//value got from the get method
$user_name = trim($_POST['user_name']);
if($user_name == ''){
echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $user_name)){
echo "invalid";
}else{
$select = mysql_query("SELECT user_id FROM staff");
$i=0;
//this varible contains the array of existing users
while($fetch = mysql_fetch_array($select)){
$existing_users[$i] = $fetch['user_id'];
$i++;
}
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not availble
echo "no";
}
else
{
//user name is available
echo "yes";
}
}
?>
I tried to add for / and \ but not succeeded.
You can also do it by using javascript & code will be:
<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode;
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="@" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
return false;
} else {
return true;
}
}
</script>
<!-- Check special characters in username end -->
<!-- in your form -->
User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>

- 15,754
- 27
- 83
- 149
-
2Dude, you've included a whole bunch of excess code that's probably not helpful. Can you cut it down to the bare minimum? And he was asking about jQuery, I'm not sure if the PHP is relevant. – Simon East Sep 21 '11 at 04:49
-
@PHP Ferrari : I am using javascript code, Your Code working fine, How can I display alert popup message if the customer enters the special character. The message like "Special Characters Not Allowed". – Gem Aug 17 '17 at 06:15
[User below code to restrict special character also
$(h.txtAmount).keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});]

- 11
- 1
Allow only numbers in TextBox (Restrict Alphabets and Special Characters)
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}

- 309
- 3
- 4
/**
* Forbids special characters and decimals
* Allows numbers only
* */
const numbersOnly = (evt) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
let inputResult = /^[0-9]*$/.test(evt.target.value);
if (!inputResult) {
evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
}
return true;
}

- 147
- 2
- 8
In HTML:
<input type="text" (keypress)="omitSpecialChar($event)"/>
In JS:
omitSpecialChar(event) {
const keyPressed = String.fromCharCode(event.keyCode);
const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
return verifyKeyPressed === true;
}
In this example it is possible to type accents.

- 51
- 1
- 1
- 5
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
$('#Description').on('change', function() {
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

- 49
- 6
A more enhanced form would be
$('input[type=text]').on('input', function() {
var c = this.selectionStart,
r = /[^a-z ]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Because it will allow you to enter space as well and it will only target the input fields with type text and wont bother the other input fields like email, password etc as normally we need special characters in email and password field

- 1
- 2
Try this JavaScript Code it's a simple way to restrict special characters from the input.
Source code: Restrict special characters
$('input').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});

- 49
- 2
- 16