Find the bug · #54 · Strings and dates Hard JavaScript
The email check lets anything through
Sign-up accepts “emails” that are whole sentences, as long as an address is in there.
On this page
The report
The sign-up form checks the email field. It accepts entries like “asha@example.com, ravi@example.com” and “not an email: a@b.co”, and the welcome emails then bounce.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Checks the email field on the sign-up form.
function isValidEmail(email) {
return /[\w.+-]+@[\w-]+\.[\w.]+/.test(email);
}Read it, then pick a line.
Does test check that the whole string matches, or only that a match exists somewhere in it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(isValidEmail('asha@example.com'));
console.log(isValidEmail('asha@example.com, ravi@example.com'));
console.log(isValidEmail('not an email: a@b.co'));It prints
true true true
It should print
true false false
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3’s regex has no anchors. test returns true if the pattern matches anywhere in the string, so any text that contains an email address somewhere passes. Anchor it with ^ and $ so the whole value has to be an email.
The fix
1// Checks the email field on the sign-up form.2function isValidEmail(email) {3 return /[\w.+-]+@[\w-]+\.[\w.]+/.test(email);3 return /^[\w.+-]+@[\w-]+\.[\w.]+$/.test(email);4}How you’d find it
- Reproduce with the reported inputs: two addresses, and a sentence containing one. Both pass.
- Each contains a valid-looking address somewhere, so the check is finding a match inside the text rather than matching all of it.
- Regex
testsearches; it doesn’t require a full match. Add^…$.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.equal(isValidEmail('a@b.co'), true);
assert.equal(isValidEmail('x a@b.co'), false);
assert.equal(isValidEmail('a@b.co y'), false);Where else this bites
- Validating a PIN code or phone number with an unanchored regex.
- Python’s
re.searchversusre.fullmatch.