Zero width characters are breaking your form validation
Some users paste text that looks empty. Your form still treats it as filled in. That is often a zero width character at work. Zero width characters take up no visible space. They still count as characters. Three common
Some users paste text that looks empty. Your form still treats it as filled in. That is often a zero width character at work.
Zero width characters take up no visible space. They still count as characters. Three common ones cause most of the trouble.
Zero width space is U+200B. It can break a word without showing a gap. Zero width joiner is U+200D. It joins emoji and some scripts into one visible unit. Hangul filler is U+3164. It looks blank on its own, and people use it to make empty looking text.
These characters are useful in some places. They also slip into forms through copy and paste. A user may copy a name from a chat app or a document. The pasted text can carry an invisible character at the start or the end. The field looks empty or normal. The stored value is not what you expect.
Here is a small example in JavaScript.
const input = "\u200B";
console.log(input); // It looks empty.
console.log(input.length); // It prints 1.
console.log(input.trim() === ""); // It prints false.
That one character breaks a simple empty check. It can also break search. A name with a hidden character will not match the same name without it. It can break duplicate checks too. Two accounts may look the same in a list, but their stored values differ by one invisible code point. Support teams then see two records for one person.
Validation should look past what the eye sees. Strip known invisible characters before you check length. Check the cleaned value, not the raw input. You can also warn the user when a value contains one of these characters. That helps them fix a paste instead of seeing a confusing error.
A simple cleanup step can use a regular expression. Remove U+200B, U+200C, U+200D, U+FEFF, and U+3164 from the input. Then trim the result. Then run your normal checks for empty values, length, and duplicates. Keep the original input in a log if you need to debug a case later. That log will show you what the user actually sent.
Detection matters as much as cleanup. If a string looks empty but has a length above zero, inspect each code point. An invisible text detector can show you the hidden characters in a pasted value. That makes the problem easy to explain to a teammate or a user.
For testing, you can build your own samples with an invisible character generator. Paste a sample into your form and watch what your validation does. Fix the cases that fail, and add a test for each one. Your future self will thank you when a strange empty string shows up in production.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.