DEV Community

David Hölkeskamp
David Hölkeskamp

Posted on

Today I Learned - maxlength

TIL - maxlength

10.07.2019

I was building a vue component, which should limit the amount of characters (alphabetical and digits) a user could enter. To implement this behaviour I did something like the following

<template>
    <input type="text" @keydown="handleKeyDown" v-model="value"/>
</template>
<script>
export default {
    name: 'BaseInput',
    data() {
        return {
            valuie: 'Lorem ipsum'
        }
    },
    methods: {
        handleKeyDown(e) {
            if(this.value.length >= 50 && e.keyCode >= 48 && e.keyCode <= 90) {
                e.preventDefault();
                return;
            }
        }
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

What this should do is enable all keys Aa-Zz and 0-9 as long as the character limit, in this case 50 has not been reached. System keys like DEL, ENTER, TAB… should not be affected by this and always work.

At the first look this may seem to work fine but as always with user input there are a lot of edge cases that are unknown at the time of implementation and could lead to bugs.

Thanks to an a lot more experienced colleague I've learned about maxlength. This is a browser implementation of limiting an input to a character count, which works like this

<input type="text" maxlength="50" />
Enter fullscreen mode Exit fullscreen mode

Same effect as above but with way less code.

Caveats

  1. Setting the value programmatically

It's still possible to programmatically set the value of a limited field e.g.

<input type="text" id="testid" maxlength="10" />

<script>
    const el = document.getElementById('testid');
    el.value = 'Text with more than ten characters';
    // This will work just fine.
</script>
Enter fullscreen mode Exit fullscreen mode
  1. maxlength is (mostly) not a proper validator

If you're working with an API where the length of inputs it important, maxlength is no replacement for proper validation as data could still be manipulated for AJAX or similar.

Sources

Top comments (2)

Collapse
 
michaeltintiuc profile image
Michael Tintiuc

Why not do value.slice(0, MAX_STR_LEN) instead? Seems to be best of 2 worlds. And of course implement server-side validation on top of that.

Collapse
 
dhkamp profile image
David Hölkeskamp

This could've definitely helped me too - it just didn't come to my mind!