I want to allow Joi to allow spaces/whitespaces in a title field of a form.
Working tomorrow with Jude.
should be allowed as wel as
Morningwalk
At this moment only the last one is validated as true. Here is my joi validation:
const schema = Joi.object().keys({ title: Joi.string().alphanum().required().max(50),
I added Regex but without result.
title: Joi.string().alphanum().required().max(50), regex( new RegExp('^\\w+( +\\w+)*$'))
What is the right way?
The .alphanum()
makes your check ignore whitespace. Also, when you define a regex using a constructor notation, you are using a string literal where backslashes are used to form string escape sequences and thus need doubling to form regex escape sequences. However, a regex literal notation is more convenient. Rather than writing new RegExp('\\\\d')
you'd write /\\d/
.
So, you may use this to allow just whitespaces:
title: Joi.string().required().max(50), regex(/^\w+(?:\s+\w+)*$/)
However, you seem to want to not allow commas and allow all other punctuation.
Use
title: Joi.string().required().max(50), regex(/^\s*\w+(?:[^\w,]+\w+)*[^,\w]*$/)
Details
^
- start of string \\s*
- 0 or more whitespaces (or, use [^,\\w]*
to match 0 or more chars other than comma and word chars) \\w+
- 1 or more word chars (letters, digits or _
, if you do not want _
, replace with [^\\W_]
) (?:[^\\w,]+\\w+)*
- zero or more repetitions of
[^\\w,]+
- 1 or more chars other than comma and word chars \\w+
- 1 or more word chars [^,\\w]*
- 0 or more chars other than comma and word chars $
- end of string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.