RegEx for Javascript to allow only alphanumeric

前端 未结 18 1439
轻奢々
轻奢々 2020-11-22 15:13

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just w

18条回答
  •  误落风尘
    2020-11-22 15:24

    Question is old, but it's never too late to answer
    
    $(document).ready(function() {
      //prevent paste
      var usern_paste = document.getElementById('yourid');
      usern_paste.onpaste = e => e.preventDefault();
    
      //prevent copy
      var usern_drop = document.getElementById('yourid');
      usern_drop.ondrop = e => e.preventDefault();
    });
    
    $('#yourid').keypress(function (e) {
      var regex = new RegExp("^[a-zA-Z0-9\s]");
      var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
      if (regex.test(str)) {
          return true;
      }
      e.preventDefault();
      return false;
    });
    

提交回复
热议问题