简体   繁体   中英

Allow chinese characters and English numbers only in textbox - Javascript

Following is my regex to accept only chinese characters and English numbers in a textbox but its failing for some scenarios like below mentioned. Let me know what I am doing wrong here.

Regex -

const regex = /[\u4E00-\u9FFF\u3400-\u4DFF\uF900-\uFAFF0-9]+/g

Failing cases -

  • 090 asffa
  • 0342eq###
  • 42242442dsfsfs

React Example code setup - https://codepen.io/anon/pen/dLQJKM

Your pattern is checking if the input contains at least one such character. As long as there will be either a number, or a Chinese character, it will consider your input as valid.

What you want is to find if there is any character that do not match this pattern. To do so, you simply need to use a negated character class [^... and then check if string.match(regex) is falsy.

 const reg = /[^\一-\鿿\㐀-\䷿\豈-\﫿0-9]+/g; const test = txt => { console.log(txt, !txt.match(reg)); }; test('090 asffa'); // false test('0342eq###'); // false test('42242442dsfsfs'); // false test('foo我'); // false test('245我吧'); // true test('245'); // true test('我吧'); // true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM