1

how to check if a javascript string doesn't contain characters like (#,$,/,@) because it's a username. I have a tried this code :

for(i=0;i<usrlength;i++) {
    if ($username.charAt(i)=='#'||$username.charAt(i)=='$') {
    }
}

but it's too long

Mayank
  • 1,291
  • 5
  • 21
  • 38
  • Possible duplicate of [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Roi Danton Jul 20 '18 at 07:07

2 Answers2

0

Put all the special characters you want to exclude in a character set inside a regular expression:

const verify = username => !/[#\$\/@]/.test(username);
console.log(verify('foo'));
console.log(verify('foo#'));
console.log(verify('foo!'));
console.log(verify('f$oo'));
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
0

You can use regex to test the string with the desired pattern:

var pattern = /[$#@/]+/;
var username = "prachi.user";
var hasInvalidChar = pattern.test(username);
if (hasInvalidChar) {
  alert("Case 1 - Invalid");
} else {
  alert("Case 1 - Valid");
}


var pattern = /[$#@/]+/;
var username = "prachi.user#$@#/";
var hasInvalidChar = pattern.test(username);
if (hasInvalidChar) {
  alert("Case 2 - Invalid");
} else {
  alert("Case 2 - Valid");
}
Prachi
  • 3,260
  • 14
  • 34