Maxlength validation counts newlines twice

Created on 3 August 2021, over 3 years ago
Updated 11 February 2023, almost 2 years ago

Steps to reproduce

  • Add a maxlength attribute to a textarea and set it to 400
  • Write a text with new lines with exactly 400 characters including some new lines where every new line counts as 1 character (like .val().length in JavaScript counts)

We found this issue with some custom JavaScript which shows to the user a counter how many characters are left. The counter shows "0 characters left" but the PHP validation claims that too many characters are used.

Proposed resolution

Problem is in FormValidator class the method performRequiredValidation(). mb_strlen($elements['#value']) counts evey new line as two characters. As suggested here https://stackoverflow.com/questions/68618268/mb-strlen-counts-new-lines-... the numbers of new lines should be deducted so that each new line becomes counted ony once:

   if (isset($elements['#maxlength'])) {
      $countCharacters = mb_strlen($elements['#value']) - substr_count($elements['#value'], "\n");
      if ($countCharacters > $elements['#maxlength']) {
        $form_state->setError($elements, $this->t('@name cannot be longer than %max characters but is currently %length characters long.', ['@name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => $countCharacters]));
      }
    }

Remaining tasks

Tests
Code review

πŸ› Bug report
Status

Needs work

Version

9.5

Component
FormΒ  β†’

Last updated 1 day ago

Created by

πŸ‡©πŸ‡ͺGermany tobiberlin Berlin, Germany

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024