If you plan to match a string of any length (even an empty string) that matches your pattern and does not start with a whitespace, use (?!\s)
right after ^
:
/^(?!\s)[a-zA-Z0-9_\s-]*$/
^^^^^^
Or, bearing in mind that [A-Za-z0-9_]
in JS regex is equal to \w
:
/^(?!\s)[\w\s-]*$/
The (?!\s)
is a negative lookahead that matches a location in string that is not immediately followed with a whitespace (matched with the \s
pattern).
If you want to add more "forbidden" chars at the string start (it looks like you also disallow -
) keep using the [\s-]
character class in the lookahead:
/^(?![\s-])[\w\s-]*$/
To match at least 1 character, replace *
with +
:
/^(?![\s-])[\w\s-]+$/
See the regex demo. JS demo:
console.log(/^(?![\s-])[\w\s-]+$/.test("abc def 123 ___ -loc- "));
console.log(/^(?![\s-])[\w\s-]+$/.test(" abc def 123 ___ -loc- "));