1

I am working on a simple PHP website where the user has to enter data in a form,

and if the user didn't enter Arabic letters I want to show a warning message "Arabic only" , I tried using the code below but it shows the warning message if I entered both Arabic or English letters.

<script>
function myFunction(){
var isArabic =  "/[\u0600-\u06FF\u0750-\u077F]/";
var x  =  document.forms["myForm"]["fname"].value;
if(x != isArabic){
    alert("arabic only");
return false;}}
</script>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
anater mj
  • 123
  • 3
  • 11
  • Your code works if you enter the string `"/[\u0600-\u06FF\u0750-\u077F]/"`. Comparing against a regex string with `==` makes no sense at all. (Unrelated but what is `x`?) – Jongware Jul 08 '18 at 14:39
  • x is text field I edited my code – anater mj Jul 08 '18 at 14:42
  • 1
    I would think that the regex `/[\u0600-\u06FF\u0750-\u077F]/` would just check if the string has at least 1 character in those ranges. A string tested against that can still contain non-arabic text. – LukStorms Jul 08 '18 at 15:00

2 Answers2

2

In your example, you need to create a RegEx object to test against.

var isArabic = /[\u0600-\u06FF\u0750-\u077F]/;
if (isArabic.test(x)){
   ...
}

There's no coercion from a string to a regular expression in JavaScript.

clint
  • 301
  • 4
  • 9
  • how I can check the opposite of this code if (isArabic.test(x)){ – anater mj Jul 08 '18 at 14:47
  • for example I want to check if there is no arabic letters – anater mj Jul 08 '18 at 14:48
  • You can just use a `!` operator. `if (!isArabic.test(x))` alternatively, you can use a not operator in your regular expression `/[^\u0600-\u06FF\u0750-\u077F]/`. Keep in mind the way your RegEx is written now, is just checking for the existence of something, if there is a string that has both characters, it'll still match. I'd add a beginning and end checks as well `/^[\u0600-\u06FF\u0750-\u077F]$/` I use a tool that's really helpful for validating: https://www.regexpal.com/ – clint Jul 08 '18 at 14:49
1

Checking whether a string equals a regex pattern isn't how you check if a string matches a particular regular expression. You need to use a function such as match() or test() which will return true if your string input matches the regular expression.

Take a look at the code snippet bellow for a working example:

let englishInput = "hello";
let arabicInput = "مرحبا";
function myFunction(userInput) {
  let regex = /[\u0600-\u06FF\u0750-\u077F]/;
  if(!userInput.match(regex)) { // Check if the regular expression matches
    alert("Only use english characters!");
  } else {
    alert("Arabic letters used!"); // Added this line just for showcasing
  }
}

myFunction(englishInput); // Will alert that english letters used
myFunction(arabicInput); // Will alert that arabic letters used
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64