I'd like to show an alert window on Auth0 universal lock if a domain in the email address field doesn't match to one from a specified list. Auth0 rules only run once authentication has taken place, I'd like something to happen before that, so I think a window alert might be a useful thing.
I've found this on the Auth0 forum which works for a single domain, in this case 'test.com' but I'd like to check multiple domains.
lock.once('signin ready', function() {
document.querySelector("div.auth0-lock-container input[name='email']").addEventListener('change',function(event){
var username = this.value;
var getDomain = function(email) { return email.match(/@(?:[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})$/i);};
if (getDomain(username) !== 'test.com') {
window.alert("Please make sure you're using an approved email address");
}
});
});
I've tried this as the if statement, but the window.alert shows for any domain, rather than the specific ones. Is that because the regex is incorrect or the if statement?
lock.once('signin ready', function() {
document.querySelector("div.auth0-lock-container input[name='email']").addEventListener('change',function(event){
var username = this.value;
var getDomain = function(email) { return email.match(/@(?:[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})$/i);};
if (!['companya.com', 'somecompany.net', 'anothercompany.org'].includes(getDomain(username))) {
window.alert("Please make sure you're using an approved email address");
}
});
});
Thanks!
The regex seems correct on first look, but the String.match
(and therefore also the function getDomain()
) does not return just a single string, but an array which contains further information about the match (or null
) if there was no match (for instance not a valid email address at all). The first element of the array contains the matched string. Docs
So you have to check first whether the return value is not null and then take the first element of the array and check with your allowed domains
var m = username.match(/@(?:[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,})$/i);
if (!m || !["domain1.com", "domain2.com", ...].includes(m[0])) {
window.alert("Please use ...");
}