views:

291

answers:

3

I have a field and want to prevent some illegal characters while showing the user as he types. How can I do this in follow example?

  $('input').bind("change keyup", function() {
   var val = $(this).attr("value");
   /*
   if (val --contains-- '"') {
    $(this).css("background", "red");
           val = val.replace('"', "");
              $(this).attr("value", val)
   }
   */
   $("p").html(val);
  });

EDIT: I should put the illegal characters in an array

var vowels = new Array('"', "<", ">", "&");
+1  A: 

Give this a try. No array, though.

    $('input').bind("change keyup", function() {
        var $th = $(this);
        $th.val( $th.val().replace(/["<>&]/g, function(str) {  return ''; } ) );
    }); 
patrick dw
A: 

You may use the indexOf to determine if a string contains a certain char...

vowels = array('"', "<", ">", "&");

$('input').bind("change keyup", function()
{
   var val = $(this).attr("value");
   var illegal = '';       
   $(vowels).each(function()
   {
      if(val.indexOf(this)!=-1)
      {
          illegal= this;
          break;
      }
   });
   if(illegal != '') 
   {
       $(this).css("background", "red");
       val = val.replace(illegal, "");
       $(this).attr("value", val)
   }
});
Alex Pacurar
+1  A: 

Try to use a regular expression.

$('input').bind("change keyup", function() {
 var val = $(this).val();
 var regex = /["<>&]/g;
 if (val.match(regex)) {
   $(this).css("background", "red");
   val = val.replace(regex, "");
   $(this).val(val);
 }
 $("p").html(val);
});

And FYI: you can replace .attr("value",val) with .val(val) and .attr("value") with .val()

UPDATE:

If you want to exclude more charecters you can just put them into the regex. If you want to exclude an character that is used to control the regex you need to escape them with \ characters to control the regex are: []()/\+{}?*+.^$

jigfox
Great! Thanks for the .val() tip also Jens. Cheers
FFish
@Jens - You should probably utilize `g` (global identifier) in case a user uses the GUI to copy and paste text with multiple excluded characters.
patrick dw
@patrick: you're absolutely right. I've changed my code
jigfox