2013-07-30 62 views
2

我有一個HTML表單,我想驗證一個正則表達式。我有一個名爲emailRegex的方法中包含的正則表達式,然後在validateEmail方法中調用它。 I「m如果一個錯誤,當它試圖將validateEmail內叫我emailRegex方法誰能告訴我,我做錯了什麼在這裏Javascript正則表單驗證

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; 

} 
} 
+1

你得到的錯誤是什麼? –

+0

比較你的正則表達式與此:http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html –

回答

3

我猜你看到一個ReferenceError:?

ReferenceError: emailRegex is not defined

你的變量,emailRegex是一個函數,而不是一個性質

這是你應該怎麼稱呼它,而不是:

var regex = this.emailRegex(); 
+0

我還有一個簡單的問題。在我的第二個正則表達式中,使用正確的語法嗎?我想檢查這兩個詞的輸入:仇恨和notCool。 – Ktown

+0

它應該是'new RegExp(「\ b(hate | notCool)\ b」,「gi」)'。 –