2
votes

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.

2
Try /^\S+$/ if you need to match a whole string that has no whitespaceWiktor Stribiżew
Please provide an example input / outputPitto
Some kinda of : space.next === someCaracter ? valid : notValid logic and this "space next" would be looked by some regex expresscristiano soares
Are you just making sure that the field does not contany any white space? In this case why not simply matchin for \s+ ?Pitto
@WiktorStribiżew it worked if the whole string has no whitespace but if I wanna some kinda of example: fullname= Alex martines ?cristiano soares

2 Answers

3
votes

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
0
votes

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'),