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
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
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'));
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");
}