0

I am using this snippet of a javascript code to validate alphabetic characters

   case "alpha_s":
            {
                ret = TestInputType(objValue, "([^A-Za-z\\s])", 
                strError, objValue.name + ": Only alphabetic characters and space 
                 allowed ");
                break;
            }

But i need the code to be able to validate Greek characters too. I tried doing this:

   case "alpha_s":
            {
                ret = TestInputType(objValue, "([^A-Za-z\\u0391-\\u03C9\\s])", strError, objValue.name + ": Only alphabetic characters and space allowed ");
                break;
}

But it had no result.

  • Possible duplicate of [Javascript - regex to remove special characters but also keep greek characters](https://stackoverflow.com/questions/23327302/javascript-regex-to-remove-special-characters-but-also-keep-greek-characters) – GalAbra May 13 '18 at 19:56
  • I tried the solutions given there, but nothing works unfortunately... – user3102627 May 13 '18 at 20:02

1 Answers1

1

Your approach is fine. There must be some problem elsewhere in your code.

Perhaps case "alpha_s" is only satisfied when there are no Greek characters. Or perhaps your TestInputType() function is getting confused by too many backslashes in the match string argument. Or maybe your document doesn't use Unicode.

The following snippet seems to work:

◽️ Update (2021-04-28): I've expanded the matching character class to include anything in the Unicode blocks \u0370 to \u03FF (Greek and Coptic) and \u1F00 to \u1FFF (Greek Extended).

function testChars() {
  var str = document.getElementById("txt").value;
  var r = document.getElementById("result");
  // Allow Roman alphabet characters (A-Z, a-z),
  // plus anything in the Unicode blocks \u0370 to
  // \u03FF (Greek and Coptic) and \u1F00 to \u1FFF
  // (Greek Extended):
  if (/^[A-Za-z\u0370-\u03FF\u1F00-\u1FFF]*$/.test(str)) {
    r.style.backgroundColor="green";
    r.style.color="white";
    r.innerHTML = "Looks OK";
  }
  else {
    r.style.backgroundColor="red";
    r.style.color="white";
    r.innerHTML = "Not OK!";
  }
}
<input type="text" id="txt" onkeyup="testChars()"
  placeholder="Type something" size="40">
<span id="result" style="padding:.1em .5em 0; border-radius:.5em"></span>
r3mainer
  • 23,981
  • 3
  • 51
  • 88