2

How can I prevent chinese character input using jquery?

$.validator.addMethod("regex", function(value, element, regexp) {
       var check = false;
            return this.optional(element) || regexp.test(value);
     },
   " Must contain only letters."
 );

This is how I check if the input is letters.

regex: /^\s*[a-zA-Z\s]+\s*$/

But How can I check the chinese character?

user2210819
  • 145
  • 2
  • 14
  • 3
    `/^\s*[a-zA-Z\s]+\s*$/` doesn't include Chinese characters in the first place. – Ry- May 31 '13 at 02:01
  • Just Chinese or Korean+Japanese+Thai+Etc? – Dave Chen May 31 '13 at 02:05
  • @DaveChen Actually just chinese is ok but its doent matter if Korean+Japanese+Thai is also blocked. Mainly chinese character – user2210819 May 31 '13 at 02:13
  • @minitech `/^\s*[a-zA-Z\s]+\s*$/` I used to check english letter only – user2210819 May 31 '13 at 02:14
  • There was a similar question [PHP regex to decipher English and Chinese characters](http://stackoverflow.com/questions/6882967/php-regex-to-to-decipher-english-and-chinese-characters) – Daniel P May 31 '13 at 02:17
  • There was a similar question on this for visual basic, you may want to simply adapt the regex solution and port it to jQuery or PHP, whatever better suits your requirements: http://stackoverflow.com/questions/10710518/strip-chinese-characters-from-a-string-vba – Chris S. May 31 '13 at 02:12

2 Answers2

4

this maybe useful:

function isChn(str){
    return /^[\u4E00-\u9FA5]+$/.test(str);
}

http://jsfiddle.net/yiqiang1314/CMv7E/

sidneyYi
  • 76
  • 3
  • this is ok for checking the chinese words. However what I want is prevent chinese words. I dont know why my checking becomes , input must be chinese instead of blocking. my question is updated – user2210819 May 31 '13 at 03:45
  • 1
    function hasChn(str){ return /[\u4E00-\u9FA5]+/.test(str); } //remove ^ and $. – sidneyYi May 31 '13 at 09:24
0

The problem isn't with your Regular Expression - you are already preventing every character besides a-z and whitespace (and there are no Chinese characters within the range of a-z). But, you've got a problem with the function logic. As it's currently written, if the field is optional, Chinese characters will be allowed. You should only skip the regexp test when it's optional and empty:

return (!value && this.optional(element)) || regexp.test(value);
gilly3
  • 87,962
  • 25
  • 144
  • 176