Mahmoud Hreib
Mahmoud Hreib

Reputation: 21

Arabic alphabets and spaces check function

I have this JavaScript function which allows me to input only Arabic characters and discard any other characters, numbers and spaces.

Whenever I enter a string like السلام عليكم it discards the space and changes it to السلامعليكم

So how can I make it accept the white space between the words.

function CheckArabicOnly(field) {
  var sNewVal = "";
  var sFieldVal = field.value;

  for (var i = 0; i < sFieldVal.length; i++) {

    var ch = sFieldVal.charAt(i);;
    var c = ch.charCodeAt(0);

    if (c < 1536 || c > 1791) {
      // Discard
    } else {
      sNewVal += ch;
    }
  }

  field.value = sNewVal;
}
<input type="text" name="department_name" value="" size='18' id="txtArabic" onchange="CheckArabicOnly(this);" required>

Thanks in advance

Upvotes: 0

Views: 75

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You could add the space char code (32) as exception in your condition like:

if ((c < 1536 || c > 1791) && c != 32) {

function CheckArabicOnly(field) {
  var sNewVal = "";
  var sFieldVal = field.value;

  for (var i = 0; i < sFieldVal.length; i++) {
    var ch = sFieldVal.charAt(i);;
    var c = ch.charCodeAt(0);

    if ((c < 1536 || c > 1791) && c != 32) {
      // Discard
    } else {
      sNewVal += ch;
    }
  }

  field.value = sNewVal;
}
<input type="text" name="department_name" value="" size='18' id="txtArabic" onchange="CheckArabicOnly(this);" required>

Upvotes: 1

Related Questions