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,351
  • 5
  • 23
  • 42
CoderTn
  • 985
  • 2
  • 22
  • 49
  • 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
  • 356,069
  • 52
  • 309
  • 320
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,478
  • 17
  • 34