2017-08-12 83 views
-1

我想用jQuery做一些驗證。當我爲每個字段創建錯誤時,我會在警報中收到2條消息。這是我的jsfiddle雙重提醒消息

function isEmail(email) { 
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
    return regex.test(email); 
} 


$("#submitButton").click(function(){ 

     var mesajEroare = ""; 

     /* verifica daca email-ul este true */ 
     if(isEmail($("#email").val()) == false) { 
     /* arata mesaj eroare */ 
     mesajEroare += "<p>Email-ul introdus nu este valid</p>"; 
     } 

     /* verificare nr telefon daca este numeric */ 
     if($.isNumeric($("#telefon").val()) == false){ 
     /* arata mesaj eroare la telefon*/ 
     mesajEroare += "<p>Numarul de telefon introdus nu este valid</p>"; 
     } 

     alert(mesajEroare); 

}); 
+2

你只想要1?也許你需要'mesajEroare ='而不是'mesajEroare + =' – putvande

+0

謝謝!祝你今天愉快! – CIonut

回答

0

在你的代碼的問題是,你是追加字符串,這意味着初始字符串mesajEroare = ""兩個字符串如果條件true結束。

根據你的要求,你應該只使用=而不是+=

+0

謝謝!祝你有美好的一天! – CIonut

+0

但是,如果用戶輸入'dd'作爲電子郵件,'aa'輸入電話,那麼應該打印這兩個錯誤。 –

+0

在這種情況下,您應該創建一個包含消息的數組,並對數組執行循環並顯示每個分隔的消息。答案是針對所問的問題。 –

1

問題是你用或不用和錯誤警報,因爲你只是外面寫的警報功能,你應該使用:

function isEmail(email) { 
     var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
     return regex.test(email); 
    } 

    $("#submitButton").click(function(){ 

    var mesajEroare = ""; 
    var fieldMissing = ""; 

    if($("#email").val() == ""){ 
    fieldMissing += "<p>email</p>"; 
    } else if (isEmail($("#email").val()) == false) { 
    mesajEroare += "<p>Email-ul introdus nu este valid</p>"; 
    } 

    if($("#telefon").val() == ""){ 
    fieldMissing += "<p>telefon</p>"; 
    } else if ($.isNumeric($("#telefon").val()) == false){ 
    mesajEroare += "<p>Numarul de telefon introdus nu este valid</p>"; 
    } 

    if($("#password").val() == ""){ 
    fieldMissing += "<p>parola</p>"; 
    } 

    if($("#passwordConfirma").val() == ""){ 
    fieldMissing += "<p>confirma parola</p>"; 
    } else if($("#password").val() != $("#passwordConfirma").val()){ 
    mesajEroare += "<p>Parola nu este la fel</p>"; 
    } 

    if(fieldMissing != ""){ 
    mesajEroare += "Nu ati completat urmatoarele casute" + fieldMissing; 
    } 

    if (mesajEroare != "") { // if found an error or more 
    console.log(mesajEroare); 
    } 

}); 
+3

或者你可以檢查是否是一個消息,而不是添加另一個變量來計數消息? – putvande

+0

正確的,謝謝@putvande –

+0

我做了你如何說,我做了一個新的字段錯誤,但看看從電子郵件和號碼電話的錯誤仍然在我的戒備...(我沒有提醒空字段)https:/ /jsfiddle.net/262eLfr7/2/ – CIonut

1

道歉稍不相關的答案,但是,如果你想有更多的比一個錯誤消息,也許你想使用換行符,而不是<p>標記。

$('#submitButton').click(function() { 
    var message = ''; 

    if (!isEmail('notAnEmail')) { 
     message += 'Email not valid\n'; 
    } 

    if (!$.isNumeric('boom')) { 
     message += 'Phone number not valid\n'; 
    } 

    if (message) { 
     alert(message); 
    } 
}); 

如果你真的只需要在一個時間一個錯誤,並使用=代替+=你只會得到您的警報的最後一個錯誤消息。

+0

我在udemy完整的web開發者付款和驗證正在做這件事,但我得到了雙重錯誤,他沒有......我不明白(謝謝你的幫助)。 – CIonut