Regex expression that matches if the string contain only spaces?

Viewed 7320

I am using formik with yup to validate a form. In one input it passes if it contains only spaces, which is not valid for my use-case. So I went through Google to find some kind of regex so if the string only has spaces it would throw some message, but I didn't find anything.

nome: string()
      .min(3, '* Deve conter no mínimo 3 caracteres')
      .required('* Este campo é obrigatório')
      .matches(/[^\s*].*[^\s*]/g, '* This field cannot contain only blankspaces'),

The problem with this is that when it reaches 3 characters even with required yup condition the validation doesn't work, and matches with regex don't block the spaces. So far I managed a work-around with: nome: values.nome.trim().replace(/\s+/g, ' ') But with the correct regex expression I can throw the error in real time.

3 Answers

You may use

/^(?!\s+$).*/
/^(?!\s+$)/
/^\s*\S.*$/
/^\s*\S[^]*$/
/^\s*\S[\s\S]*$/

The first two regexps will match any string that is not equal to 1 or more whitespaces.

The last third, fourth and fifth match a string that contains at least one non-whitespace char.

See the regex demo

Details

  • ^ - start of string
  • (?!\s+$) - a negative lookahead that fails the match if there are 1 or more whitespaces and end of string immediately to the right of the current location
  • .* - 0 or more chars other than line break chars, as many as possible
  • \s*\S.* - zero or more whitespaces, a non-whitespace, and then any zero or more chars other than line break chars
  • \s*\S[^]* / \s*\S[\s\S]* - same as above but any chars including line breaks can appear after the non-whitespace char
  • $ - end of string

Since you want to match in case any white space is present please try:

nome: string()
      .min(3, '* Deve conter no mínimo 3 caracteres')
      .required('* Este campo é obrigatório')
      .matches(/^(\S+$)/g, '* This field cannot contain only blankspaces'),

.matches(/^(\S+$)/, '* This field cannot contain only blankspaces') worked for me as well.

Mark the capital S but not the small s

Related