3

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?

Community
  • 1
  • 1
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88

2 Answers2

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.

user513951
  • 12,445
  • 7
  • 65
  • 82
1

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'));
Muzafar Ali
  • 1,362
  • 1
  • 12
  • 18