2016-11-15 14 views
1

我想檢查多行字符串以防止用戶輸入電子郵件和電話號碼,並通知他們錯誤消息「ERR1」(例如,電話號碼和電子郵件是不允許的)。正則表達式跳過電子郵件/電話引發錯誤的新行(輸入鍵) - HTML/AngularJS

我用下面的正則表達式(RE):

$rootScope.RejectEmailPhoneNo='^(?:(?!(@|([0-9]{3}(|-|_|\.)[0-9]{3})|[0-9]{4}|([0-9]{2}(|-|_|\.)[0-9]{2})|([0-9](|-|_|\.)[0-9](|-|_|\.)[0-9]))).)+$' 

所需的結果: RE不應該允許多位數的數字(例如,4454,313 345,22 14,546-343,1 2 2 4等)和'@'符號。允許任何其他字符(使用'點')。

問題:但是,什麼情況是:當用戶輸入回車鍵,他們得到通知錯誤消息「ERR1」的。 當我改變了RE允許換行符使用DOTALL運營商,我得到錯誤信息「ERR1」甚至當我進入「ABCDE」

$rootScope.RejectEmailPhoneNo='^(?:(?!(@|([0-9]{3}(|-|_|\.)[0-9]{3})|[0-9]{4}|([0-9]{2}(|-|_|\.)[0-9]{2})|([0-9](|-|_|\.)[0-9](|-|_|\.)[0-9])))[\s\S])+$' 

當我使用「(?S)」,而不是[\ S \ S] - 它允許所有字符包括@和多位數字。

我的問題是:

(1)我怎麼會做出這樣的正則表達式不拋出新行錯誤 - 但是必須拋出一個錯誤,只有當用戶進入電子郵件(或至少@)和多位數號碼?

上述RE在上下文中使用:

 <md-input-container class="md-block" flex-gt-sm> 
    <label>Description</label> 
    <textarea md-maxlength="900" rows="1" ng-model="job.description" ng- required=true name="description" type="text" 
    pattern={{RejectEmailPhoneNo}} 
    ng-class="{ error : profile_form.description.$touched && profile_form.description.$error.required,typed : profile_form.description.$valid && profile_form.description.$touched && profile_form.description.$dirty }" 
    class="ng-pristine ng-untouched ng-valid ng-valid-pattern ng-valid-maxlength" 
    aria-multiline="true" aria-invalid="false"></textarea> 

    <div ng-messages="fulltime_form.description.$error"> 
    <div ng-message="required">Please provide description.</div> 
    <div ng-message="pattern">Phone numbers and emails are not allowed.</div> 

**(2)如果RE可以用於通過控制器功能「說明」進行檢查 - 如何寫它作爲一個功能?在角JS **

回答

1

不知道如果我的理解是正確的

所需的結果:RE不應該允許多位數的數字(例如,4454,313 345 ,22 14,546-343,1 2 2 4等)和'@'符號。允許任何其他字符(使用'點')。

問題但是,會發生什麼情況是:當用戶輸入回車鍵時,會收到錯誤消息「ERR1」的通知。當我改變了RE允許換行符使用DOTALL運營商,我得到錯誤信息「ERR1」甚至當我進入「ABCDE」

的問題是:你需要搜索內部電子郵件的發生一個字符串。 如果有電子郵件,然後顯示錯誤

如果這是你的問題,然後解決方案是非常簡單的,上面的代碼應該解決這個問題:

const regex = /([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)/i; 
const str = `hello, 

this is an email test 
i am verifying whether there is or not an email in this message 

regards, 
[email protected]`; 

let m; 

if ((m = regex.exec(str)) !== null) { 
    if(m.length > 0){ 
     alert('there is email(s). Show the error'); 
    } 
}else{ 
    alert('there is no email. Success!'); 
} 

它提醒錯誤只有如果在文本中的電子郵件地址。

+0

謝謝,我已經更新了我的問題,以提供更多關於使用RE的上下文。該代碼是角度格式 - 不知道如何適應你給的JS代碼。 – Srilekha

相關問題