I am using regex to validate my logic. My regex is to allow all character or words except on word naveen
.
I tried like this
let str = "123";
let str2 ="naveen" // special case Exact naveen text not allow .
let str3 ="naddn"
let str4 ="nad$$dn"
let str5 ="naveen56"
let pattern = /[a-z] /;
let result1 = str.match(pattern);
let result2 = str2.match(pattern);
let result3 = str3.match(pattern);
let result4 = str4.match(pattern);
let result5 = str5.match(pattern);
console.log(result1) // expected null // correct
console.log(result2) // expected null // current showing naveen text (INCORRECT)
console.log(result3) // expected naddn // correct
console.log(result4) // expected nad$$dn // correct
console.log(result5) // expected naveen56 // correct
is there any way to fix this issue ?
here is my code https://jsfiddle.net/ac3m052y/
CodePudding user response:
You don't need a regex, a simple string compare will do. Here is an example with string compare and regex compare:
const input = [
"123",
"naveen", // special case Exact naveen text not allow
"naddn",
"nad$$dn",
"naveen56"
].forEach(str => {
let strResult = (str === 'naveen') ? 'not allowed' : 'Ok'
let regexResult = (/^naveen$/.test(str)) ? 'not allowed' : 'Ok'
console.log(str ' => ' strResult ' (string compare), ' regexResult ' (regex compare)')
});
Output:
123 => Ok (string compare), Ok (regex compare)
naveen => not allowed (string compare), not allowed (regex compare)
naddn => Ok (string compare), Ok (regex compare)
nad$$dn => Ok (string compare), Ok (regex compare)
naveen56 => Ok (string compare), Ok (regex compare)
CodePudding user response:
This code only check which "naveen" word. and I used php
if(!preg_match("/^((naveen))/", "naveen")){
echo "correct";
}else{
echo "incorrect";
}
CodePudding user response:
Result is this
let str = "123";
let str2 ="naveen" // special case Exact naveen text not allow .
let str3 ="naddn"
let str4 ="nad$$dn"
let str5 ="naveen56"
let pattern = /^(naveen){1}$/;
let result1 = !pattern.test(str);
let result2 = !pattern.test(str2);
let result3 = !pattern.test(str3);
let result4 = !pattern.test(str4);
let result5 = !pattern.test(str5);
console.log(result1) // expected null // correct
console.log(result2) // expected null // not naveen text
console.log(result3) // expected naddn
console.log(result4) // expected nad$$dn
console.log(result5) // expected naveen56