Home > Back-end >  Restrict spaces and accept only Latina letters
Restrict spaces and accept only Latina letters

Time:10-04

I'm new to regexp. I'm trying to figure out how to allow only Latin letters, prohibit spaces, but so that my other regexps still work.

I have 6 steps for password. 4/6 I already covered. But have problems with the remaining 2 steps.

matches(/^(?=.*[a-z])/, "mustContainsLowerCase") works
matches(/^(?=.*[A-Z])/, "mustContainsUpperCase") works
matches(/^(?=.*\d)/, "mustContainsNumber") works
matches(/[^\dA-Za-z]/, "mustContainsSpecialCharacter") works

matches(/^(?=.* )/, "Should not contains spaces "), <- Not working
matches(/??/, "must contains only Latin letters"), <- I have no ideas 


const valid = "a1W@";
const invalid1 = "a1W@ a1W@";
const invalid2 = "a1W@法" (法 forbidden, only Latin letters allow)

I will be grateful for any help, as I have no ideas left.

CodePudding user response:

The ^(?=.* ) regex requires at least one regular space in the string since (?=...) is a positive lookahead. You need a negative lookahead here, ^(?!.* ). Alternatively, /^(?!\S*\s)/ can be used to disallow any whitespace in the string.

To disallow any non-ASCII letter inside a string, you can use the ECMAScript 2018 compliant pattern like

/^(?!.*[^\P{Alphabetic}a-zA-Z])/u

Here, [^\P{Alphabetic}a-zA-Z] defines any Unicode letter that does not fall into the A-Z and a-z ranges.

  • Related