-1

I want to check whether my userid is having any special character apart from alphanumeric characters (a-z,A-Z,0-9). The below regex is failing...what would be the correct way?

var testStr = '3278|3278.3000.2506.60200000.1100.000.0000.0||703"68*[70"8';
var splitTeststr = testStr.split('|');
alert(splitTeststr[0]);
/* alert('Length of splitStr is : ' +splitTeststr.length); */
if (splitTeststr.length == 4) {
    var userId = splitTeststr[3].trim();
    alert('userId before removing junk : ' +userId);
    var letterNumber = /^[0-9a-zA-Z]+$/;
    
    if((userId.match(letterNumber))){
        alert('UserId contains junk : ' +userId);
        
    }else{
        alert('Userid is fine');
    }
}
Cris-123
  • 28
  • 5

1 Answers1

0

There is an issue in your regex, the correct one is /[^0-9a-zA-Z]/:

function testUserId(userId){
    console.log('userId before removing junk : ' +userId);
    var letterNumber = /[^0-9a-zA-Z]/;
    if((userId.match(letterNumber))){
        console.log('UserId contains junk : ' +userId);
    }else{
        console.log('Userid is fine');
    }
 }

// letter and numbers
testUserId("34293483209jfeoiAAAAsojf");
// numbers
testUserId("1234");
// letters
testUserId("aaaBBBBB");
// rejected
testUserId("aa!aBBB!..BB");
Greedo
  • 3,438
  • 1
  • 13
  • 28