0

I need to stop the users to enter text using alphabet different from the Latin one (aka english).

I am using the following function based on a regex but I have some issues:

  1. The validation fails if the input is empty
  2. The validation pass if the input is mixed for example aaaaффффф

I solve the first point using a simple if anyway it would be nice if the regex take care of this case too The second point is what I care more.

function validate_latin(v){
    var regex = new RegExp("[\u0000-\u007F\u0080-\u00FF]");
    if (v != '') {
        return regex.test(v);
    }
    return true;
}

p.s. I googled and found other similar question but none is complete or cover this sceniario

WonderLand
  • 5,494
  • 7
  • 57
  • 76
  • Use anchors and a quantifier. That will only allow the ascii characters specified. This is only looking for 1 ascii character then anything else is allowed. – chris85 Jan 15 '17 at 16:01
  • Possible duplicate of [Learning Regular Expressions](http://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Jan 15 '17 at 16:01
  • like chris85 said, if your latin sub-pattern is working then it is just `/^[\u0000-\u007F\u0080-\u00FF]+$/` – Scott Weaver Jan 15 '17 at 17:36
  • 1
    @sweaver2112 thx I confirm this is working fine, if you can put it in answer I will be glad to accept it – WonderLand Jan 19 '17 at 07:36

1 Answers1

0

if your Latin subpattern is working for you, the solution is straightforward. ^ and $ anchors will prevent partial matching (whole string/line must match), and the +, which means 'one or more', disallows the empty string:

/^[\u0000-\u007F\u0080-\u00FF]+$/
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43