2017-02-14 58 views
0

工作,我做了一個非常簡單的電子郵件驗證,看起來像這樣:表單驗證閉合不角2

function validateEmail(formControl: FormControl): {[key: string]: any} { 
    const regExp = new RegExp(`^[\\w.%+\-][email protected][\\w.\-]+\.[a-zA-Z]{2,16}$`); 
    return regExp.test(formControl.value) ? null : { email: true }; 
} 

這工作時,我把它添加到在反應形式方法驗證列表。

但是,當我改變了上述函數:

function validateEmail(): ValidatorFn { 
    return (formControl: FormControl): {[key: string]: any} => { 
     console.log(formControl.value); 
     const regExp = new RegExp(`^[\\w.%+\-][email protected][\\w.\-]+\.[a-zA-Z]{2,16}$`); 
     return regExp.test(formControl.value) ? null : { email: true }; 
    } 
} 

然後驗證不起作用。我沒有收到錯誤消息。控制檯輸出什麼都不顯示。

我在做什麼錯?

回答

0

你應該通過controlAbstractControlValidatorFn,這意味着你的代碼應該如下所示:

function validateEmail(): ValidatorFn { 
    return (control: AbstractControl): {[key: string]: any} => { 
    console.log(control.value); 
    const regExp = new RegExp(`^[\\w.%+\-][email protected][\\w.\-]+\.[a-zA-Z]{2,16}$`); 
    return regExp.test(control.value) ? null : { email: true }; 
    } 
} 

應該解決您的問題,我有一個解決類似這樣的非常相似驗證:

export function emailValidator(): ValidatorFn { 
    return (control: AbstractControl): { [key: string]: any } => { 
    const email = control.value; 

    if ('' === email || null === email) { 
     return null; 
    } else { 
     return emailRegEx.test(email) ? null : { invalidEmail: { email } }; 
    } 
    }; 
} 

其中emailRegEx被定義爲函數外的常量,當傳遞的值爲空字符串或null時,函數返回null。