0

http://jsbin.com/cunejafehe/edit?html,js,console,output

var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
   
function myFunction(e){
  console.log(e.value);
  if(reg.test(e.value))
   {
     return false;
   }
}
<input onkeyup="myFunction(this)" type="text">

I wonder why above code doesn't work, what I want to do is allow only these character to be in the input : a-z and 1-9 including 0, and these character -'#(),"

Alien Xu
  • 193
  • 2
  • 3
  • 12

2 Answers2

2

Please have a look at this approach. Here i am passing an event object instead of DOM element reference and then we are checking it against Regx expression.

var reg = /^[a-zA-Z\d\s\-'#(),"0-9]*$/
   
function myFunction(e){
  var c = String.fromCharCode(e.which)
  console.log(c);
  if(reg.test(c))
   {
     return true;
   }
 else
   return false;
}

$(document).ready(function(){
  $( "#mytextbox" ).keypress(function( e) {
    return myFunction(e);
  });
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Inline function : <input onkeypress="return myFunction(event)" type="text">
<br/>

Binding a function : <input id="mytextbox" type="text">
vijayP
  • 11,432
  • 5
  • 25
  • 40
0

The test method belongs to a RegExp object, since you're not using that you should change reg.test(c) to c.match(reg) inside myFunction.

Moreover you are working on the full value of the field by passing this. I guess you can do something like this, even if not very elegant:

 var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
 
function myFunction(e){
  if (!e.value.match(reg)) {
    e.value = e.value.slice(0, -1);
  }
}
<input onkeyup="myFunction(this)" type="text">
SamWhan
  • 8,296
  • 1
  • 18
  • 45
Lud
  • 482
  • 2
  • 9