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>
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" />
Same effect as above but with way less code.
Caveats
- 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>
- 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.
Top comments (2)
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.This could've definitely helped me too - it just didn't come to my mind!