Reputation: 707
I am trying to limit user's input as followings.
I want to prevent user to enter non-english characters (like Chinese, Korean, etc.).
export const isValidPasswordChar = str => {
const regex = /^[~`!@#$%^&*()_+\-=\[\]\\{}|;':",./<>?a-zA-Z0-9]$/;
if(regex.test(str)){
return false
}
return true;
};
And unit test
it('should not allow foreign chars-1', ()=>{
const str = '안';
expect(isValidPasswordChar(str)).toBe(false);
});
The above unit test worked before but for some reason, unit test is keep failing. Is there something I am missing here?
Upvotes: 5
Views: 6284
Reputation: 37755
You're on right path
^[~`!@#$%^&*()_+=[\]\\{}|;':",.\/<>?a-zA-Z0-9-]+$
-
at end so not needed to escape] and / and \
you don't need to escape other charactersconst isValidPasswordChar = str => {
const regex = /^[~`!@#$%^&*()_+=[\]\{}|;':",.\/<>?a-zA-Z0-9-]+$/;
return regex.test(str)
};
console.log(isValidPasswordChar('/'))
console.log(isValidPasswordChar('`1234567890-=;:,./'))
console.log(isValidPasswordChar('HelloPasword1234~!@#$%^&*()_+'))
console.log(isValidPasswordChar('汉字'))
Upvotes: 7