4

I have some string and I need to check if this string:

a) consists of 3 words b) contains ONLY cyrillic symbols and spaces

My code:

var isValid;
isValid = function(s) {
  return s && s.split(" ").length === 3 && /[а-яА-Я ]/.test(s);
};

But this code doesn't work, because isValid('a b c') returns 'true'. What is my mistake? Thanks in advance!

malcoauri
  • 11,904
  • 28
  • 82
  • 137
  • Try this [link](http://stackoverflow.com/questions/1716609/how-to-match-cyrillic-characters-with-a-regular-expression) ? – huwence Sep 22 '15 at 06:29

1 Answers1

7

Try this:

var isValid = function(s) {
    return s && s.split(" ").length === 3 && /^[\u0400-\u04FF ]+$/.test(s);
};
Ty Kroll
  • 1,385
  • 12
  • 27
  • Here is a quick explanation on using unicode character classes. You need unicode hex codes for your regex. I looked up Cyrillic, found it here: http://unicode.org/charts/PDF/U0400.pdf. Cyrillic characters go from 0x0400 to 0x04FF. In regex, use \u followed by the 4-character code: \u0400, \u04ff. Make that a character class and you're off. More info here: http://www.regular-expressions.info/unicode.html – Ty Kroll Sep 22 '15 at 16:22