Regular Expression for Not Allowing Spaces in the Input Field

Regular expression for not allowing spaces in the input field

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

RegEx: 8-20 characters, but no spaces allowed

Remove the dot.

^[^-\s]{8,20}$

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

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).

Javascript regular expression to not allow space in a textfield

maskRe: /[^ ]/

[^ ] means anything except the space character. If you wanted to match all whitespace and not just the space character, use /\S/

regex to disallow space at begining and end and allow only one space between characters

This validates the given String as you requested: