如果用户名/电子邮件与特定域不匹配,则显示窗口警报

问题描述

如果电子邮件地址字段中的域与指定列表中的一个域不匹配,我想在Auth0通用锁定上显示一个警报窗口。 Auth0规则仅在进行身份验证后才运行,我希望在此之前发生一些事情,因此我认为窗口警报可能是有用的事情。

我在Auth0论坛上找到了该域名,该论坛适用于单个域,在本例中为“ test.com”,但我想检查多个域。

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})|(?:(?:[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");
        }
    });
});

我已经尝试将其作为if语句,但是window.alert会显示任何域,而不是特定域。是因为正则表达式不正确还是if语句?

lock.once('signin ready',})$/i);};
        if (!['companya.com','somecompany.net','anothercompany.org'].includes(getDomain(username))) {
            window.alert("Please make sure you're using an approved email address");
        }
    });
});

谢谢!

解决方法

乍看之下,正则表达式似乎是正确的,但是String.match(以及函数getDomain())不仅返回单个字符串,而且还返回包含有关该匹配的进一步信息的数组(或null)(如果没有匹配项(例如根本不是有效的电子邮件地址))。数组的第一个元素包含匹配的字符串。 Docs

因此,您必须首先检查返回值是否不为null,然后获取数组的第一个元素并检查允许的域

var m = username.match(/@(?:[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 ...");
}