[英]Javascript: Validation alerts
我需要做的是以下幾點:
name
或email
為空,則提醒“空字段” email
中不包含@,則提醒“不良電子郵件” 如果正確填寫name
和email
則提示“成功”
function test10(email, name){ if(email=="") { alert("empty field");} else if(email.indexOf("@")<0){ alert("bad email");} if(name=="") { alert("empty field");} }
到目前為止,這是我想出的,我想使其盡可能簡單。 現在,當我兩個都填寫時,我又該如何表達“成功”? 我只需要用javascript做就可以了。
可能值得一提的是,我對javascript還是很陌生,所以如果您認為這很愚蠢,請盡量避免侮辱自己,我只是想在這里學習。
嘗試這個:
function test10(email, name){
// The || is a boolean "OR" , so if (email equals "") OR (name equals "")
// then alert the failure reason.
if(email=="" || name == "") {
alert("empty field");
return false;
}
if(email.indexOf("@") == -1){
alert("bad email");
return false;
}
//Conditions are met.
alert("Succes!");
return true;
}
這完全按照您指定的方式工作。
您可以在函數的末尾放置一個final else子句並從那里警告成功消息,或者在遇到錯誤時可以從函數返回,請確保在遇到無效輸入時阻止該函數繼續運行。 然后,您可能會在函數結束時收到一條警告,說成功,因為只要輸入中仍然有錯誤,您就永遠無法達到目標。
像這樣:
function test10(email, name){
if (email === "" || name === "") {
alert("empty field");
return false;
}
if(email.indexOf("@")<0){
alert("bad email");
return false;
}
// If we get here, the input is all good!
alert("success");
return true;
}
這樣,您只會一次警告用戶有關一個錯誤的信息,讓她有時間來解決該錯誤,而不是在未滿足您的規則的情況下互相拋出三個警告。
從函數返回false / true的好處是,如果輸入無效,則可以使用該函數停止表單提交。
替代驗證方法
借助HTML5,引入了數據表單驗證,從而提供了使用諸如required
和pattern
類的屬性進行驗證的本機選項。 如果您使用新的<input type="email">
瀏覽器還可以對電子郵件輸入執行驗證
MDN上對此有更廣泛的閱讀 。
嘗試這個
function test10(email, name){
if(email=="" || name=="") {
alert("empty field");}
else if(email.indexOf("@")<0){
alert("bad email");}
else{
alert("success");}
}
只需在每種錯誤情況下添加return
語句
function test10(email, name)
{
if(email=="") {
alert("empty field");
return false;
}
if(email.indexOf("@")<0){
alert("bad email");
return false;
}
if(name=="") {
alert("empty field");
return false;
}
alert("success");
return true;
}
注意:您需要在表單事件中添加onsubmit="return test10(email,name);"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.