I am trying to validate the number of characters allowed in a textarea in the PHP backend.
I’ve been using Laravel’s validation rule:
'textarea' => ['required', 'string', 'max:50'],
Most of the times it works, and the string length of the textarea matches. However sometimes there are extra characters coming to the PHP backend which makes the length not match the one seen on the frontend.
It happens with unseen spaces, or maybe with non-English languages, but it’s hard to know when it will happen.
Is there a way to get the same input size in PHP as the one in the frontend?
The issue right now is that in the frontend I allow up to 50 characters, but PHP sees it as more than 50 sometimes.
If it’s possible to do it with vanilla PHP, I will simply remove the Laravel validation and do it with vanilla PHP, but I am not sure how, because even when I echo the input with PHP I see those rogue characters even when using mb_strlen
This is the input for example with characters counter:
let textarea = document.getElementById('textarea-with-counter');
let characterCountSpan = document.getElementById('character-count');
textarea.addEventListener("keyup", (event) => {
characterCountSpan.innerText = event.target.value.length;
});
<p>Number of characters: <span id="character-count"></span></p>
<textarea id="textarea-with-counter" rows="3" maxlength="50"></textarea>