hinewwiner
hinewwiner

Reputation: 707

regex - only allow English(lower or upper), numbers, special characters

I am trying to limit user's input as followings.

  1. English characters (a to z or A to Z)
  2. Numeric characters ( 0 to 9 )
  3. 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?

Upvotes: 5

Views: 6284

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

You'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('汉字'))

Upvotes: 7

Related Questions