Question

I need to check if the name field is only Hebrew letters[א-ת], now the function work good, but if I enter letters from two different languages like "abcdאבג" it ignores and return true and I need it to return false, thank you

function justHeb(str){
    ok = true;
        for (var i=0;i<str.length&&ok;i++)
        {
            if (!str[i].match(/[א-ת]/))
            {
                ok=false;
                return false;
            }
            else return true;
        }
}

function firstName(str){
    if(justHeb(document.getElementById("firstname").value)){
        return true;
    }
    else {
        return false;
    }
}

function checkAll(){
    if(firstName()){
        alert("true");
    }
    else 
        alert("false");
}
Was it helpful?

Solution

You need to move the return true; to outside the for loop. Otherwise your code will accept any string that simply starts with a Hebrew character.

function justHeb(str){
    var ok = true;
        for (var i=0;i<str.length&&ok;i++)
        {
            if (!str[i].match(/[א-ת]/))
            {
                ok=false;
                return false;
            }
        }
    return true;
}

Now, you could simplify even further by letting the regular expression engine do that work for you:

function justHeb(str) {
  return /^[א-ת]*$/.test(str);
}

The leading ^ means that the match must start at the beginning of the string. The * says to accept a sequence of zero or more characters in that range, and finally the $ says that the match must end at the end of the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top