0

I need to create regular expression that should accept both English and Arabic letters. How can I do this?

HTML:

<input type="text" class="ico1" name="firstname" id="firstname" placeholder="enter name " title="enter name ">

JS:

$("#register-form").validate({
  rules: {
    firstname: {
      required: true,
      minlength: 2,
      regx: /^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/
    },
  },
  messages: {
    firstname: {
      required: "<font color='red'>  please enter name </font>",
      minlength: "<font color='red'>minimum length is 2</font>",
      regx: "<font color='red'>enter only english or arabic letters</font>"
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});
timolawl
  • 5,434
  • 13
  • 29
arun kumar
  • 85
  • 1
  • 7

2 Answers2

2

I had to check several things and here ar emy findings:

  • You need to use [\u0600-\u06FF] regex to match an Arabic character in JS
  • The full regex you need is var regx = /^[a-zA-Z\u0600-\u06FF,-][\sa-zA-Z\u0600-\u06FF,-]*$/; (see demo)
  • The JQuery validation plugin does not have regx rule, you need to use pattern from the additional-methods.js
  • You can also use a dynamic message for the minlength rule: use minlength: jQuery.validator.format("At least {0} characters required!")

See updated JS demo:

var regx = /^[a-zA-Z\u0600-\u06FF,-][\sa-zA-Z\u0600-\u06FF,-]*$/; // E.g. هل بعتم بيتكم في نيويورك
$.validator.setDefaults({
  submitHandler: function() {
   alert("submitted!");
  }
 });

$("#register-form").validate({
  debug: true, // REMOVE THIS, IT IS FOR DEMO DEBUG ONLY!!!
  rules: {
    firstname: {
      required: true,
      pattern: regx,
      minlength: 2
    },
  },
  messages: {
    firstname: {
      required: "please enter name",
      minlength: jQuery.validator.format("At least {0} characters required!"),
      pattern: "enter only english or arabic letters"
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="register-form" name="register-form">
 <input type="text" class="ico1" name="firstname" id="firstname" placeholder="enter name " title="enter name "/>
 <input type="Submit"/>
</form>
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Use the following regex pattern with \p{InArabic} and \p{Latin} Unicode scripts:

...
regx : /^[\p{InArabic}\p{Latin}-,]+(\s?[\p{InArabic}\p{Latin}-, ])*$/
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105