有没有Javascript LIKE语句?

时间:2010-05-11 08:37:12

标签: javascript html

我想这样做但不知道如何在JavaScript中执行此操作。

if (Email == "*aol.com" || Email == "*hotmail*" || Email == "*gmail*" || Email == "*yahoo*") 
    {
     alert("No Hotmail, Gmail, Yahoo or AOL emails are allowed!");  
     return false;
    }

有什么方法吗?

4 个答案:

答案 0 :(得分:6)

首先,我认为您的搜索过于通用。 (例如,如果某人有电子邮件地址,“ shotmail@mydomain.com ”该怎么办?

试试这个:

var notAllowed = /@(?:aol|hotmail|g(?:oogle)?mail|yahoo)\.com$/i;
// You may want to cover other domains under .co.uk etc.

if ( notAllowed.test(emailAddress) ) {
    alert("No Hotmail, Gmail, Yahoo or AOL emails are allowed!");  
    return false;
}

我不得不问,为什么禁止人们使用这些电子邮件地址? (出于兴趣)

另外,这真的应该在服务器端完成(我假设你没有使用SSJS)

答案 1 :(得分:3)

使用JavaScript REGEXP对象。有关示例,请阅读W3schools pagetheir tutorial。如果您遇到任何问题,请在此处发布,我们将详细介绍:)

var Email = 'testmail@yahoo.com';

var mail_pattern=new RegExp("/aol.com|hotmail|gmail|yahoo/");
if (mail_pattern.test(Email)) {
 alert("No Hotmail, Gmail, Yahoo or AOL emails are allowed!");  
}
else {
alert("mail ok")
}

答案 2 :(得分:0)

最好的方式是REGEXP。快速简单的事情可能是indexOf方法,但它是如此有限。

http://www.quirksmode.org/js/strings.html#indexof

答案 3 :(得分:0)

只是因为人们建议使用正则表达式,你也可以以编程方式进行:

(我有点建议你不了解JavaScript)

function validateEmail (email) {
    // Checks if whatever variable submitted is a string.
    // This line is NOT useful if you're sure of whatever being sent to the function,
    // but otherwise it'll save your ass for a runtime error.
    if (email.constructor != String) return false;

    // I'm not sure the search patterns are 100 % (they probably ain't),
    // but the @'s should make the search less generic.
    var emailsNotAllowed = ["@aol.com", "@hotmail.", "@live.", "@gmail.", "@google.", "@yahoo."];
    // Convert the email address to lower case, so you're sure nothing is going wrong with the patterns.
    email = email.toLowerCase();
    // Loop through all the patterns, and check if one of them matches the email address provided.
    for (var i = 0; i < emailNotAllowed.length; i++) {
        // The indexOf method will return zero if the string could not be found.
        // Otherwise, it will return a positive number, which in JavaScript validates to a true condition.
        if (email.indexOf(emailsNotAllowed[i])) {
            alert("No Hotmail, Gmail, Yahoo or AOL emails are allowed!");
            return false;
        }
    }
}

希望它能解释自己;)

同样建议,应该在服务器端执行检查作为绝对最小值,否则您将没有安全性。但是,对于可用性,客户端检查也是好的。