Cleaning user input in JavaScript means turning whatever a person typed into a predictable shape before your code looks at it, with no stray spaces, no hidden characters, and one consistent case. Validating it means deciding whether the result is actually acceptable and, when it is not, saying why it is not. The earlier lessons in this module gave you all the tools that you need for this. You saw the string methods that matter, you learned to build messages with template literals, you learned how to split text into pieces and join it back together, and you learned how to search for text and replace it. This lesson puts all of those tools to work on the text that real people type into forms.
The previous lesson in this module covered "Searching and Replacing in Strings", and this lesson is the last one in the JavaScript Strings module.
What does cleaning actually involve?
Four operations, in this order, cover almost every case that you will meet. Normalise the characters, strip the ones that nobody can see, collapse the runs of whitespace, and trim the ends. Normalising first matters, because some of the other steps behave differently depending on the character forms that they are given.
function cleanText(input) {
return input
.normalize('NFKC')
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
const raw = ' Ada\u200B Lovelace ';
console.log(JSON.stringify(raw));
console.log(JSON.stringify(cleanText(raw)));
Each step has its own job. The normalize('NFKC') call folds characters that look identical but are encoded differently, so full-width letters from a Japanese keyboard become ordinary ASCII letters. The replace with the character class removes the invisible ones, including the zero-width space that some keyboards and copy-paste from a PDF sprinkle through the text. The replace(/\s+/g, ' ') call turns every run of whitespace into a single space, and trim removes the space at the beginning and the space at the end.
Notice that trim on its own would have left the middle gap in place. The raw value has three spaces between the two words, and trimming only touches the two ends of a string. The whitespace class \s is also wider than the space character, because it covers tabs, newlines, the non-breaking space, and other Unicode spaces. A value that was pasted from a word processor therefore rarely survives as it is.
Which invisible characters survive a trim?
The zero-width space is the interesting one, because it looks like nothing at all and it survives a trim. Unicode puts it at U+200B, and it is not whitespace by the standards that JavaScript follows, so trim leaves it alone and so does \s. The result is a string that is three characters longer than a human would count, and a comparison such as value === 'Ada Lovelace' that mysteriously fails. The byte-order mark at U+FEFF is the opposite case, because it is whitespace as far as \s is concerned, so it disappears on its own. Stripping it explicitly still does no harm, and it documents the intent.
This is also why JSON.stringify earns its place in the snippet above. When you print a string with console.log, the zero-width space is invisible in the terminal, so the two lines look identical to the naked eye. Wrapping the value in JSON.stringify escapes the unusual characters, and the difference between the two outputs becomes obvious.
Should you change the case of what somebody typed?
Yes for comparison, and usually no for storage. If a user types [email protected], the address that they want is the lower-case version, but the name that they want to see on the screen is the one that they typed. The safe pattern is to keep the original value and to derive a comparison key from it, which is the same idea that you met in the previous lesson when you used toLowerCase() to compare two addresses.
const email = ' [email protected] ';
const key = email.trim().toLowerCase();
console.log(key);
console.log(key === '[email protected]');
console.log('I'.toLowerCase());
console.log('I'.toLocaleLowerCase('tr'));
The last two lines show why toLowerCase and toLocaleLowerCase are not the same function. In Turkish, the lower-case form of the letter I is a dotless ı rather than an i, and the locale-aware version follows that rule while the plain version always produces an i. For most applications the plain version is fine, but if your users span several locales then the locale-aware one is the correct choice. Otherwise a Turkish user can end up unable to log in with an address that looks perfectly right to them.
One field that you should not clean in this way is a password. Spaces at the start or the end of a password are sometimes deliberate, and lower-casing it changes the secret that the user chose. Trim nothing, change nothing, and compare exactly what was typed.
How do I validate a field without writing a monster regular expression?
Validate one rule at a time, and give every rule its own error message. A single regular expression that checks the name, the email, and the age together is unreadable, it cannot be tested, and it is impossible to report against, because a user who gets it wrong is told nothing about which part was wrong.
function validateSignup(form) {
const errors = {};
const name = form.name.trim();
const email = form.email.trim().toLowerCase();
const age = form.age.trim();
if (name.length < 2) {
errors.name = 'Enter at least 2 characters.';
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.email = 'Enter a valid email address.';
}
if (age === '') {
errors.age = 'Age is required.';
} else if (!Number.isFinite(Number(age))) {
errors.age = 'Age must be a number.';
} else if (Number(age) < 13) {
errors.age = 'Age must be 13 or more.';
}
return { ok: Object.keys(errors).length === 0, errors };
}
console.log(validateSignup({ name: 'Ada', email: '[email protected]', age: '36' }));
console.log(validateSignup({ name: 'A', email: 'ada@example', age: 'twelve' }));
console.log(Number.isFinite('42'));
console.log(Number.isFinite(Number('42')));
The last two lines hold the numeric trap in one place. Number.isFinite refuses to convert anything, so given the string '42' it answers false, because a string is not a number. The global Number function does convert, so Number('42') is 42. It also converts the empty string to 0, which is why the age field is checked for emptiness before the number check runs. Without that check, an empty age field would arrive as the number zero and sail through to the range test. This is the same trap that you met in the earlier lesson about turning strings into numbers, and it is worth looking for in every form that you build.
The email pattern above is deliberately simple, and it means something, an at sign, something, a dot, something. It rejects the obvious mistakes, and a stricter check belongs on the server, where you can consult a real list of disposable domains and a mail delivery check.
When is normalising the same as validating?
It never is, but the two get confused because they sit next to each other. Normalising a phone number means removing the formatting that a person added to make it readable. Validating it means deciding how many digits are actually required. If you only normalise, you have thrown away the information that would have told you that the number was wrong.
function digitsOnly(value) {
return value.replace(/\D/g, '');
}
function normalisePhone(input) {
const digits = digitsOnly(input);
if (digits.length !== 10) {
return null;
}
return digits.slice(0, 3) + '-' + digits.slice(3, 6) + '-' + digits.slice(6);
}
console.log(normalisePhone('(207) 946-0018'));
console.log(normalisePhone('207946001'));
console.log(normalisePhone('call me'));
The function strips everything that is not a digit, and then it checks how many digits it ended up with. The first input is a phone number written three different ways, and it comes back in one consistent shape. The second has nine digits and the third has none, so both of them return null. That is the honest answer, rather than an empty string that a caller might mistake for a real value.
Rules that keep bad data out
- Clean, then validate. Validate the cleaned value, so that whitespace and case never decide the outcome.
- Keep the original. Store what the user typed next to the cleaned version, so that you can show it back and audit the difference.
- Strip what nobody can see. Zero-width characters and byte-order marks survive
trim, so remove them explicitly. - Never convert silently.
Number.isFiniterefuses to convert, so use the globalNumberonly when you mean to. - Leave passwords alone. No trimming, no case folding, and no normalisation of the secret itself.
- Report each rule separately. One message per field is better than one message for everything.
Try it yourself: build a cleanSignup(form) function that takes { name, email, password } and returns { ok, values, errors }, where values holds the cleaned name and email along with the untouched password. Test it with these three inputs and check each result by eye: { name: ' Ada\u200B Lovelace ', email: ' [email protected] ', password: ' hunter2 ' }, { name: 'A', email: 'not-an-email', password: '' }, and { name: 'Grace Hopper', email: '[email protected]', password: 'x' }. The first one should pass and should produce the name Ada Lovelace with the email in lower case. The second one should fail on both the name and the email, and it should keep the password exactly as it was typed, including the space around it. The third one should fail on the length of the password with a message that says so. Once that works, add a rule that rejects a password shorter than eight characters, and check that the error object grows a password key instead of replacing the others.