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

javascript - How to regex match entire string instead of a single character - Stack Overflow

programmeradmin0浏览0评论

I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.

Now the problem is it gives the following result:

r = /[\u0600-\u06FF]/

r.test("abcd")      // false - correct
r.test("@#$%^")     // false - correct
r.test("س")         // true  - correct
r.test("abcd$$#5س") // true  - should be false
r.test("abcdس")     // true  - should be false

If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?

I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.

Now the problem is it gives the following result:

r = /[\u0600-\u06FF]/

r.test("abcd")      // false - correct
r.test("@#$%^")     // false - correct
r.test("س")         // true  - correct
r.test("abcd$$#5س") // true  - should be false
r.test("abcdس")     // true  - should be false

If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?

Share Improve this question edited May 23, 2017 at 11:33 CommunityBot 11 silver badge asked Feb 27, 2014 at 8:42 Mohd Abdul MujibMohd Abdul Mujib 14k8 gold badges69 silver badges91 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You need to add ^ and $ anchors to the regular expression, as well as a + to allow multiple characters.

Try this:

/^[\u0600-\u06FF]+$/

I'm not sure if "Arabic spaces" that you mentioned are included in the character range there, but if you want to allow white space in the string then just add a \s inside the [] brackets.

You can explicitly allow some keys e-g: numpad, backspace and space, please check the code snippet below:

function restrictInputOtherThanArabic($field)
{
  // Arabic characters fall in the Unicode range 0600 - 06FF
  var arabicCharUnicodeRange = /[\u0600-\u06FF]/;

  $field.bind("keypress", function(event)
  {
    var key = event.which;

    // 0 = numpad
    // 8 = backspace
    // 32 = space
    if (key==8 || key==0 || key === 32)
    {
      return true;
    }

    var str = String.fromCharCode(key);
    if ( arabicCharUnicodeRange.test(str) )
    {
      return true;
    }

    return false;
  });
}

// call this function on a field
restrictInputOtherThanArabic($('#firstnameAr'));
发布评论

评论列表(0)

  1. 暂无评论