jQuery keyup() illegal characters

前端 未结 3 1085
时光说笑
时光说笑 2021-01-25 17:08

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          


        
相关标签:
3条回答
  • 2021-01-25 17:18

    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 characters 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: []()/\+{}?*+.^$

    0 讨论(0)
  • 2021-01-25 17:18

    Give this a try. No array, though.

        $('input').bind("change keyup", function() {
            var $th = $(this);
            $th.val( $th.val().replace(/["<>&]/g, function(str) {  return ''; } ) );
        }); 
    
    0 讨论(0)
  • 2021-01-25 17:26

    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)
       }
    });
    
    0 讨论(0)
提交回复
热议问题