最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin9浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论