admin 管理员组

文章数量: 1184232

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?

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?

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
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)