admin管理员组文章数量:1435859
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 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?
Share Improve this question edited Mar 18, 2019 at 13:46 Tichel asked Mar 18, 2019 at 13:23 TichelTichel 5312 gold badges12 silver badges26 bronze badges 6-
1
What if you replace
new RegExp('^\w+( +\w+)*$')
with/^\w+( +\w+)*$/
? – Wiktor Stribiżew Commented Mar 18, 2019 at 13:24 - still not allow spaces – Tichel Commented Mar 18, 2019 at 13:28
-
1
Probably, you need to remove
.alphanum()
– Wiktor Stribiżew Commented Mar 18, 2019 at 13:29 - Works. Now only add punctuation marks to regex. cheers – Tichel Commented Mar 18, 2019 at 13:33
-
So, you mean
/^\w+(?:\W+\w+)*$/
? – Wiktor Stribiżew Commented Mar 18, 2019 at 13:34
1 Answer
Reset to default 3The .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 mas 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 ma 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 ma and word chars\w+
- 1 or more word chars
[^,\w]*
- 0 or more chars other than ma and word chars$
- end of string.
本文标签: javascriptJOI how to allow empty spaces and punctuationStack Overflow
版权声明:本文标题:javascript - JOI how to allow empty spaces and punctuation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745655109a2668662.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论