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 -'#(),"

2
  • May be a return true; instead of false? Commented Jun 17, 2016 at 8:47
  • It works for me with <input onkeypress="checkInput(event)" type="text"> and var reg = /[a-zA-Z\d\s\-'#(),"]/; function checkInput(e) { var ok = reg.test(String.fromCharCode(e.charCode)); if (!ok) e.preventDefault(); } Commented Jun 17, 2016 at 8:56

2 Answers 2

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">

Sign up to request clarification or add additional context in comments.

3 Comments

what if I want to bind instead of using inline function? return on inline function look bad to me.
binding a keypress is also possible. You can do it like $( "#mytextbox" ).keypress(function( e) {
@AlienXu - updated the code snippet for binding instead of inline function.
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">

2 Comments

Edited the answer. I actually tested this and it works.
Yup... Now it works. Took the liberty to edit the question to test the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.