I am trying to limit user's input as followings.
- English characters (a to z or A to Z)
- Numeric characters ( 0 to 9 )
- All special characters (~`!@#$%^&*()_+-=[]{}|;':",./<>?)
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?
I am trying to limit user's input as followings.
- English characters (a to z or A to Z)
- Numeric characters ( 0 to 9 )
- All special characters (~`!@#$%^&*()_+-=[]{}|;':",./<>?)
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?
Share Improve this question asked Jul 21, 2019 at 10:30 hinewwinerhinewwiner 7071 gold badge16 silver badges27 bronze badges 1-
1
You have to repeat the character class using
+
and escape the backslash ^[~`!@#$%^&*()_+\-=[]\\{}|;':",.\/<>?a-zA-Z0-9]+$ See regex101./r/CGxQhx/1 – The fourth bird Commented Jul 21, 2019 at 10:32
1 Answer
Reset to default 7You're on right path
^[~`!@#$%^&*()_+=[\]\\{}|;':",.\/<>?a-zA-Z0-9-]+$
- You can move
-
at end so not needed to escape - except
] and / and \
you don't need to escape other characters
const 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('汉字'))