Search code examples
javascriptphphtmlmaxlength

HTML, Javascript, and PHP - maxlength able to be changed through inspect element


Back with an issue which I'm sure you guys will find easy to fix. Whilst using the maxlength function in html, I noticed that users can simply use inspect element to modify the maxlength deeming it pretty useless.

Basic example of max-length:

<input type="text" name="username" maxlength="250" alt="Please don't change my maxlength">

I'm looking for a solution in Javascript or PHP at preventing this code manipulation on the server side.

Thanks in advance.


Solution

  • There's no point trying to work around this in JS as users can simply bypass your validation code and manually submit a form to your site which has a value longer than the specified maxlength. So you need to deal with it in PHP:

    $username = $_POST['username'] ?? '';
    if (strlen($username) > 250) {
        // return some sort of error to the user
        exit;
    }