3

I have the following functions

JavaScript

function lettersNumbersOnly(string){
   if (/[A-Za-z0-9]/.test(string)) {
     console.log('Clean');
   }else{
     console.log('Not Matching');
   }
}

$(".test-input").change(function(){
  lettersNumbersOnly($(this).val());
});

If I were to put letters and numbers into that .test-input field, I get the "Clean". BUT if I put characters like !2@$% etc. I still get the "Clean" which is not what I want. I just want strictly letters and numbers. Any suggestions?

Taylor Foster
  • 1,103
  • 1
  • 11
  • 24

1 Answers1

7

Use start and end anchors for complete string match and + for one or more repetition of character class.

if (/^[A-Za-z0-9]+$/.test(string)) 
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188