Email checking
by kdrdgn
HTML
<label>
First name
<input value="Corey" name="firstName" autofocus/>
</label>
<label>
Last name
<input value="Baxter" name="lastName" />
</label>
<label>
Email
<input value="[email protected]" name="email" />
</label>
<button id="message" tabindex="-1"></button>
<button id="check">Check email</button>
CSS
body {
font-family: "Helvetica Neue", Arial, sans-serif;
color: #444;
}
label {
display: block;
margin-top: 20px;
}
input {
display: block;
padding: 10px;
font-size: 17px;
width: 300px;
margin-top: 3px;
}
button {
padding: 5px 10px;
}
#message {
display: block;
background: transparent;
border: 0;
height: 30px;
margin-bottom: 20px;
color: firebrick;
text-decoration: underline;
cursor: pointer;
}
JavaScript
function checkForCloseMatch(longString, shortString) {
// too many false positives with very short strings
if (shortString.length < 3) return '';
// test if the shortString is in the string (so everything is fine)
if (longString.includes(shortString)) return '';
// split the shortString string into two at each postion e.g. g|mail gm|ail gma|il gmai|l
// and test that each half exists with one gap
for (let i = 1; i < shortString.length; i++) {
const firstPart = shortString.substring(0, i);
const secondPart = shortString.substring(i);
// test for wrong letter
const wrongLetterRegEx = new RegExp(`${firstPart}.${secondPart.substring(1)}`);
if (wrongLetterRegEx.test(longString)) {
return longString.replace(wrongLetterRegEx, shortString);
}
// test for extra letter
const extraLetterRegEx = new RegExp(`${firstPart}.${secondPart}`);
if (extraLetterRegEx.test(longString)) {
return longString.replace(extraLetterRegEx, shortString);
}
// test for missing letter
if (secondPart !== 'mail') {
const missingLetterRegEx = new RegExp(`${firstPart}{0}${secondPart}`);
if (missingLetterRegEx.test(longString)) {
return longString.replace(missingLetterRegEx, shortString);
}
}
// test for switched letters
const switchedLetters = [
shortString.substring(0, i - 1),
shortString.charAt(i),
shortString.charAt(i - 1),
shortString.substring(i + 1),
].join('');
if (longString.includes(switchedLetters)) {
return longString.replace(switchedLetters, shortString);
}
}
// if nothing was close, then there wasn't a typo
return '';
}
function checkForDomainTypo(userEmail) {
const domains = ['gmail', 'hotmail', 'outlook', 'yahoo', 'icloud', 'mail', 'zoho'];
const [leftPart, rightPart] = userEmail.split('@');
for (let i = 0; i < domains.length; i++) {
const domain = domains[i];
const result = checkForCloseMatch(rightPart,...