Home  >  Q&A  >  body text

Special characters causing problems with Joi validation

<p>I want to limit the content in the text box to 250 words. I am using joi validation to achieve this. It should count all characters (including special characters) and only allow 250 words. But I encountered the following problem. </p> <ol> <li><p>As soon as the first special character appears, even after 3 words, I get a joi validation error saying "This section cannot exceed 250 characters". </p> </li> <li><p>When I copy and paste content from a PDF, my screen freezes. So I think there is something wrong with my joi schema. </p> </li> </ol> <pre class="brush:php;toolbar:false;">description1: Joi.string().regex(/^(([\w\s,."'()-] )\b[\ s,.]*){0,250}$/).options({ language: { string: { regex: { base: 'This part cannot exceed 250 characters' } } }).label("This part" ),</pre> <p>Can anyone help me? </p>
P粉267791326P粉267791326385 days ago497

reply all(1)I'll reply

  • P粉916760429

    P粉9167604292023-09-01 00:35:05

    This may work:

    /^\s*(?:\S+\s+){0,249}\S*\s*$/
    

    is different from \w in your original regular expression that only matches [a-zA-Z0-9_], the special symbol \S matches Any non-space character. Because character sets \S and \s are completely different, this should avoid any problems related to catastrophic backtracking.

    explain:

      Zero or more spaces at the beginning of
    • \s*. These are not counted.
    • (\S \s ) A word consisting of 1 or more non-space characters followed by 1 or more space characters.
    • {0,249} Repeat up to 249 times
    • \S* Optionally add an extra word at the end, which should not end with a space. This is the 250th word, so the number of lines above needs to be 249 not 250.

    This only goes back the length of the last word, so may be slow if the last word is very long. However, growth cannot be exponential, so it should not cause Joi to collapse.

    reply
    0
  • Cancelreply