-2

I have one textbox. i want to restrict the user to type the html unsafe characters like

" < > # % { } | \ ^ ~ [ ] `.

Can anyone tell me what regular expression i have to use in javascript function to restrict the user to type the unsafe characters in textbox.

John
  • 107
  • 9
  • What is meaning of *`unsafe characters`*.? – ketan Jan 13 '16 at 06:46
  • 1
    What have you tried so far? I am 100% sure that there are lots of threads like this already just in SO and not in google. – choz Jan 13 '16 at 06:49
  • the characters which i mentioned below in the question which will break the html code. i want to dynamically bind the textbox value into alt tag in img – John Jan 13 '16 at 06:49

4 Answers4

1

Assuming you mean alpha-numeric ... You'll want something like the following -- Obviously this is crude with no actual elements selected etc... And you'll want a function (keypress) or something wrapped around it.

var cleantext = /^[0-9a-zA-Z]+$/;  
if(yourtextbox.value.match(cleantext))   
  {  
   return true;  
  }  

For Just the characters above, a small function to check maybe?

var s = yourtextbox.value;
var charTest = (function() {
var cleanText = /^[<>#%{}|\\^~\[\]]$/i;
return function(s) {
return cleanText.test(s);
}
})();

Or even:

var s = yourtextbox.value;
function isClean(s) {
return ['"', '<', '>', '#', '%', '{', '}', '|', '\\', '^', '~', '[', ']', '`', '.'].indexOf(s) !== -1
}
Zak
  • 6,976
  • 2
  • 26
  • 48
1

You can use below js:

var specialChars = "!@#$^&%*()+=-[]\/{}|:<>?,.";
for (var i = 0; i < specialChars.length; i++) {
stringToReplace = stringToReplace .replace(new RegExp("\\" + specialChars[i], 'gi'), '');
}

REFERENCE: HERE

Community
  • 1
  • 1
Chonchol Mahmud
  • 2,717
  • 7
  • 39
  • 72
1

Try this: JSFiddle

myFunction = function(event) {
    var x = event.which || event.keyCode;
    document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
    if(x.toString().match(/^(60|62|35)$/)){
         document.getElementById("alert").innerHTML = "This is unsafe character";
    }else {
        document.getElementById("alert").innerHTML = "";
    }
}

Use the keycode to check the character is safe or not. Here 60 => "<"; 62 => ">" and 35 => "#" , just add the keycode for character you want.

Vegeta
  • 1,319
  • 7
  • 17
1

You said you are having text box right....? ok then in that you have to handle the onkeypress event

You can use the following function to restrict the users to type the unsafe characters in the textbox.

function keypresshandler(event)
{
     var charCode = event.keyCode;
     //Non-numeric character range
     if (charCode > 31 && (charCode < 48 || charCode > 57))
     return false;
}