2

我有一个要使用正则表达式验证的 HTML 表单。我将正则表达式包含在一个名为 emailRegex 的方法中,然后在 validateEmail 方法中调用该方法。当它尝试在 validateEmail 中调用我的 emailRegex 方法时出现错误。谁能告诉我我在这里做错了什么?

var validation={

emailRegex: function() {//new email Regular Expression for validateEmail method
    return /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+  ([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;
},

validateEmail: function(value) {

    var regex = this.emailRegex;//takes value found in emailRegex

    var offensiveWords = new RegExp(/\b(hate|notCool)b/); //offensive words regular expression

    var email = document.getElementById("email");

    var compactEmail = function(){//takes the value of the email form element and takes out any white spaces
        var emailValue = email.value;
        var compacted = emailValue.replace(" ","");
        return compacted;
    }

    if(!regex.test(compactEmail())){//checks for a valid email address against regex from emailRegex method

        alert("Please enter a valid email address");
        email.focus();

        return false; 
    }

    if(!offensiveWords.test(compactEmail())){//checks for the offensive words found in offensiveWords regular expression.

        alert("Your email address contains an offensive word");
        email.focus();

        return false;
    }

    return true;

}
}
4

1 回答 1

3

我猜你看到的是ReferenceError

ReferenceError:未定义 emailRegex

您的变量emailRegex是一个函数,而不是一个属性。

你应该这样称呼它:

var regex = this.emailRegex();
于 2013-07-30T04:17:33.947 回答