JS Regex allowing incorrect characters

后端 未结 2 1030
既然无缘
既然无缘 2021-01-21 09:44

I have a comments field for SEPA payments and such a field has the following restrictions when it comes to what a user can type:

a b c d e f g h i j k l m n o p          


        
2条回答
  •  我在风中等你
    2021-01-21 09:48

    The problem is due to the way you declared the regex via a RegExp constructor. The hyphen should be escaped twice to be treated as a literal hyphen there.

    This is the range it allowed:

    It is advised to use a literal notation when your regex is known from the start, and best practice is to use the hyphen at the end of the character class range in order to avoid escaping it.

    To match 0 or more characters in your range, you need to use

    var regex = /^[a-z0-9\/?:().,\'+\s-]*$/i;
    

    See this demo fiddle

    If you plan to match at least 1 (or more), keep your +? (or +, it will work the same way in your case) quantifier.

    $('.no_special_chars').keypress(function (e) {   
      var regex = /^[a-z0-9\/?:().,\'+\s-]*$/i;
      console.log(String.fromCharCode(!e.charCode ? e.which : e.charCode));
      var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    
      // Allow tab, left/right arrow, backspace and delete. Then proceed to validation
      if (e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 8 || e.keyCode == 46) {
         return true;
      }
    
      // Do not allow returns in the comment field
      if (e.keyCode == 13) {
         return false;
      }
    
      if (regex.test(str)) {
         return true;
      }
    
      return false;
    });
    
    

提交回复
热议问题