javascriptregex

Regular expression in javascript to not allow only whitespaces in a field but allow string with whitespaces and also allow empty field


I need regular expression to not allow only whitespaces in a field(the user should not enter just whitespaces in the field) but it can allow completely empty field and it can also allow string with whitespaces in between.

For example if I enter strings such as "This is a test" or "testing", the regular expression should pass validation. Also, If I don't enter anything in the field, it should pass validation. It should fail if I enter only whitespaces.

I tried the below mentioned ones but they fail.

1) ^[^-\s][a-zA-Z0-9_\s-]+$ - doesn't allow me to enter string with whitespaces in between

2) ^[^-\s][\w\s-]+$ - doesn't allow me to enter a string


Solution

  • Are spaces allowed at the beginning of your string?

    If so, then something like that should work:

    ^$|.*\S+.*
    

    Otherwise this one should do the trick:

    ^$|^\S+.*
    

    Explanation:

    I'll explain the version without leading spaces because the other one is just a slightly expanded version of it.

    First, we check if the String is empty with ^$. This is explained in another question here Regular expression which matches a pattern, or is an empty string.

    ^ marks the beginning of the string which we want to check for a match.

    \S+ checks for non-whitespace characters. The + makes sure, that there needs to be at least one of them or more. This includes spaces, tabs, new-lines, etc.

    .* matches any characters (denoted by the dot) and any number of them or none (denoted by the *).


    This all assumes, that you need to match the whole string though. If that is not the case for you, you could shorten the expression to:

    ^$|\S+
    

    or

    ^$|^\S+
    

    If the user input has matches for the first expression then you'll know the string he entered contains characters which are not space or is empty. If it has matches for the second expression you additionally know that it starts with non-space characters.

    These expressions are of course only two of a lot of possible expressions. I chose them because they are easy to read and explain(in my opinion at least).