, into the page that embeds the form, after the form's // embed code (Seamless or Iframe), then fill in the settings below. MIT licence. // Guide: https://email-validation.org/docs/guides/cognito-forms/ // // It uses only Cognito Forms' client-side events (cognitoforms.com/support "Client-side events"): a "beforeSubmit" // handler, registered with Cognito.on(), checks the address when the respondent presses Submit and calls // event.preventDefault() when the result is one you stop; the handler returns a Promise, which delays the submit until // the check answers (at most 3 seconds). Valid and unknown addresses, a slow or failed check and a key that is not a // browser key never stop the form. (() => { const SETTINGS = { // The Email field's JSON name, as Developer Mode shows it (a field in a section: 'Section.Email'). emailField: 'Email', // A browser key: Dashboard -> API keys -> Create key -> "On a public web page", with the address of the page that // embeds your form as an allowed origin and a daily credit cap. Anyone can read it in the page, so never paste any // other key here. browserKey: 'YOUR_BROWSER_KEY', // 'https://api-eu.email-validation.org' to have the addresses validated in the EU. api: 'https://api.email-validation.org', // The results that stop the form: any of 'invalid', 'disposable', 'catch_all'. stop: ['invalid', 'disposable'], messages: { invalid: 'This address cannot receive email. Please check it.', disposable: 'Please use a permanent address, not a disposable one.', catch_all: 'We could not confirm this address. Please use another one.', }, }; /** How long a submit waits for the check before the form goes anyway. */ const WAIT_MS = 3000; /** A request still open after this is dropped (the address then passes). */ const ABORT_MS = 10000; /** The API's shortest `timeout` (seconds): a check that needs longer ends as a free `unknown`. */ const SERVER_TIMEOUT_S = 5; const STOPPABLE = ['invalid', 'disposable', 'catch_all']; const key = String(SETTINGS.browserKey).trim(); if (key.slice(30, 37) !== 'browser') { console.warn('email-validation.org: not a browser key, so nothing is checked.'); return; } const api = window.Cognito; if (!api || typeof api.on !== 'function') { console.warn( 'email-validation.org: Cognito Forms’ embed script is not on this page above the snippet, so nothing is checked.', ); return; } const path = String(SETTINGS.emailField).split('.'); const stop = SETTINGS.stop.filter((s) => STOPPABLE.includes(s)); /** One check per address on this page: the address in lower case -> a promise of its status, or null. */ const checks = new Map(); /** The checks that have answered: the address in lower case -> its status, or null. */ const settled = new Map(); /** Set after a refused key or no credits (401, 402, 403): nothing more is sent from this page. */ let off = false; /** The Email field's value in the entry Cognito Forms is about to submit (event.data.entry), or ''. */ const addressOf = (entry) => { let value = entry; for (const part of path) value = value && typeof value === 'object' ? value[part] : undefined; const address = typeof value === 'string' ? value.trim() : ''; return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address) && address.length <= 320 ? address : ''; }; const ask = async (address) => { if (off) return null; const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), ABORT_MS); try { const res = await fetch(`${SETTINGS.api}/v1/validate`, { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: address, timeout: SERVER_TIMEOUT_S }), credentials: 'omit', // the page's origin at most, never its address (which could hold an answer in its query) referrerPolicy: 'strict-origin', signal: ctrl.signal, }); if (res.status > 400 && res.status < 404) off = true; if (!res.ok) return null; const body = await res.json(); return body && typeof body.status === 'string' ? body.status : null; } catch { return null; } finally { clearTimeout(timer); } }; const check = (address) => { const id = address.toLowerCase(); if (!checks.has(id)) { checks.set( id, ask(address).then((status) => { settled.set(id, status); return status; }), ); } return checks.get(id); }; /** The status, or null once `ms` have passed without one. */ const within = (promise, ms) => new Promise((resolve) => { const timer = setTimeout(() => resolve(null), ms); promise.then((status) => { clearTimeout(timer); resolve(status); }); }); const stopped = (status) => typeof status === 'string' && stop.includes(status); /** Stops the submit as Cognito Forms' documented example does: a message, then event.preventDefault(). */ const refuse = (event, status) => { window.alert(SETTINGS.messages[status]); event.preventDefault(); }; api.on('beforeSubmit', (event) => { const data = event?.data; // The form already shows a validation message: Cognito Forms keeps it from being sent anyway. if (!data || data.hasErrors) return undefined; const address = addressOf(data.entry); if (!address) return undefined; const id = address.toLowerCase(); // The same address, already checked on this page (a second Submit): decided at once. if (settled.has(id)) { const status = settled.get(id); if (stopped(status)) refuse(event, status); return undefined; } // A returned Promise delays the submit until it settles (Cognito Forms' "Advanced usage"): at most WAIT_MS. return within(check(address), WAIT_MS).then((status) => { if (stopped(status)) refuse(event, status); }); }); })();