2017-02-17 64 views
0

當我嘗試通過正則表達式驗證電子郵件時,我遇到了一個路障。嘗試使用內置JavaScript .test()方法進行正則表達式測試時,出現未定義的函數錯誤。引用這些類型的函數時是否使用某種特殊關鍵字?在反應本地調用js函數

謝謝!我感謝你的意見。

這些是導致問題的兩段代碼。

class LoginForm extends Component { 

state = { email: '', password: '', warning: '', loading: false, color:  '#FFFFFF' }; 

    onButtonPress() { 
     const { email, password } = this.state; 

    this.setState({ loading: true }); 
    this.setState({ warning: '' }); 

    if (this.verifyEmail(email)) { 
    firebase.auth().signInWithEmailAndPassword(email, password) 
    .then(this.onLoginSuccess.bind(this)) 
    .catch(() => { 
     firebase.auth().createUserWithEmailAndPassword(email, password) 
     .then(this.onLoginSuccess.bind(this)) 
     .catch(this.onLoginFail.bind(this)); 
    }); 
    } 
    else { 
    this.onLoginFail.bind(this); 
    } 
} 

    verifyEmail = (email) => { 
    const regex = '^[a-zA-Z0-9_.+-][email protected](?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)? (gmail)\.com$'; 
    return regex.test(email); 
    } 
+0

你似乎是試圖調用['RegExp.prototype.test'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/RegExp/test)。嘗試將您的字符串轉換爲實際的RegExp – Hamms

+0

Yeap,這很有道理。我在一段時間裏並沒有和js混淆。謝謝! – Gabe

回答

0

您正則表達式只是一個字符串,但不是真正的正則表達式,你應該建立一個像這樣的正則表達式:

verifyEmail = (email) => { 
    const regex = /^[a-zA-Z0-9_.+-][email protected](?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)? (gmail)\.com$/; 
    return regex.test(email); 
} 

正則表達式經常重複使用。所以我建議你這樣做:

const regex = /^[a-zA-Z0-9_.+-][email protected](?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)? (gmail)\.com$/; 

var verifyEmail = (email) => { 
    return regex.test(email); 
} 
+0

請解釋你的答案,而不是隻是傾銷代碼片段。 –

+0

這是做了詭計,出於某種原因,我記得過去不得不使用引號。謝謝! – Gabe

+0

你可以像這樣創建一個正則表達式: var regex = new Regex('^ [a-zA-Z0-9 _。+ - ] + @(?:(?:[a-zA-Z0-9- ] + \。)?[a-zA-Z] + \。)?(gmail)\。com $') –