Sunil
Sunil

Reputation: 21396

Javascript to allow only certain characters?

I have a text-box into which a user can input a comment. The comment could be a combination of alphabets ( lowercase or uppercase) or digits or @ or semi-colon or colon or period or comma or $ or forward slash or space or - or _. I have tried using the following function but it does not test for $ or space or - or _. How can I include these also in this JavaScript function? I also want to allow an empty string in input.

function alphanumeric(inputtxt) 
{  
  var letters = /^[0-9a-zA-Z]+$/; 
  if(inputtxt.value.match(letters)) 
  { 
    alert('Your registration number have accepted : you can try another'); 
    document.form1.text1.focus(); 
    return true; 
  } 
  else 
  { 
    alert('Please input alphanumeric characters only'); 
    return false; 
  } 
} 

ANSWER is as below ( provided with the help of xdazz):

   function alphanumeric(inputtxt) 
{  
  var letters = /^[\w\d\s@;:.,-/$/]*$/; 
  if(inputtxt.value.match(letters)) 
  { 
    alert('Your registration number have accepted : you can try another'); 
    document.form1.text1.focus(); 
    return true; 
  } 
  else 
  { 
    alert('Please input alphanumeric characters only'); 
    return false; 
  } 
} 

Upvotes: 1

Views: 11884

Answers (1)

xdazz
xdazz

Reputation: 160833

Try the regex below.

var letters = /^[\w\d\s$@;.,-/]+$/; 

Upvotes: 6

Related Questions