5

Currently, I am using /^[a-zA-Z.+-. ']+$/ regex to validate incoming strings.

When the incoming string is empty or only contains whitespace, I would like the code to throw an error.

How can I check for empty string using regex? I found some solutions but none are helpful.

2
  • if(string.match(/^\s?=*$/g).length > 0) // Not valid Commented Aug 8, 2017 at 11:44
  • Please don't use the jQuery Validate tag when the code in this question has nothing to do with this plugin. Edited. Thanks. Commented Aug 8, 2017 at 14:16

3 Answers 3

4

You may use

/^(?! *$)[a-zA-Z.+ '-]+$/

Or - to match any whitespace

/^(?!\s*$)[a-zA-Z.+\s'-]+$/

The (?!\s*$) negative lookahead will fail the match if the string is empty or only contains whitespace.

Pattern details

  • ^ - start of string
  • (?!\s*$) - no empty string or whitespaces only in the string
  • [a-zA-Z.+\s'-]+ - 1 or more letters, ., +, whitespace, ' or - chars
  • $ - end of string.

Note that actually, you may also use (?!\s+) lookahead here, since your pattern does not match an empty string due to the + quantifier at the end.

Sign up to request clarification or add additional context in comments.

Comments

4

Check if the string is empty or not using the following regex:

/^ *$/

The regex above matches the start of the string (^), then any number of spaces (*), then the end of the string ($). If you would instead like to match ANY white space (tabs, etc.), you can use \s* instead of *, making the regex the following:

/^\s*$/

Comments

1

To check for empty or whitespace-only strings you can use this regex: /^\s*$/

Example:

function IsEmptyOrWhiteSpace(str) {
    return (str.match(/^\s*$/) || []).length > 0;
}

var str1 = "";
var str2 = " ";
var str3 = "a b";

console.log(IsEmptyOrWhiteSpace(str1)); // true
console.log(IsEmptyOrWhiteSpace(str2)); // true
console.log(IsEmptyOrWhiteSpace(str3)); // false

2 Comments

Global flag is unnecessary.
Whoops, was for testing, removed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.