Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alya_alsiyabi's avatar

Limit number of characters in input field with PHP

hi Is there away to limit the number of characters in php for example in html we use maxlength

     <input type = "text" name = "first_name" value = "" maxlength = "40" />

What about php what can we use?

0 likes
13 replies
alya_alsiyabi's avatar

@MichalOravec is it only from controller ? we can not validate from view? I mean my instructor told to validate it from both controller and view, so I was thinking to convert all the php to html or find away to validate php from the view

Tray2's avatar
Tray2
Best Answer
Level 73

@alya_alsiyabi No, there isn't with php, you will have to use Javascript for that unless you are satisfied with just setting length in your html

iftekhs's avatar

Well you can use these snippets ->

// For Laravel

$request->validate([
            'first_name' => 'required|max:20',
            'for_number' => 'required|digits:20',
        ]); 

// For native php

if(strlen($input) > 20)
{
   echo "Input cannot be higher than 20 characters";
}

// For javascript 

if(input.length > 20) {
	alert('Input cant be higher than 20 characters.');
}

alya_alsiyabi's avatar

@iftekhs is it only from controller ? we can not validate from view? I mean my instructor told to validate it from both controller and view, so I was thinking to convert all the php to html or find away to validate php from the view

iftekhs's avatar

@alya_alsiyabi Well I don't think it's possible from the view because the HTML is sent to the client-side what you can do is validate it in the view using javascript. and validate in the controller using the $request->validate([]).

1 like
tykus's avatar

@alya_alsiyabi PHP runs on the server not in the browser - the maxlength attribute will work. But you must be aware that a malicious user can modify the markup, and therefore validate in the Controller (or Form Request) as well

1 like
Snapey's avatar

Please note that the character count can be wrong if you allow html input in the field. User does not get to enter as many characters as they think they should because of hidden html. The same for multi-byte characters.

1 like

Please or to participate in this conversation.