2017-06-29 102 views
-2

我有一個表單,我需要使用它的行動。 一個用於獲取在字段中輸入的信息並將用戶重定向到另一個頁面,另一個用於檢查電子郵件驗證。 的電子郵件驗證是第一個領域,其他領域是正常的 這裏是我的代碼:一種形式的兩個動作

<form name="myform" class="login" action="getinfo.php" method="POST"> 
 
<input name="f1" type="text" placeholder="email" autofocus/> 
 
<input name="f2" type="password" placeholder="example2"/>
這是檢驗第一場對電子郵件中的JS代碼:

function validateForm() { 
var x = document.forms["myForm"]["email"].value; 
var atpos = x.indexOf("@"); 
var dotpos = x.lastIndexOf("."); 
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { 
    alert("Not a valid e-mail address"); 
    return false; 
} 

我不知道如何在一種形式中使用兩個動作 在此先感謝,希望我已經足夠簡潔和準確。

+1

建議在服務器端執行驗證,因爲JS可以被禁用,並且在某些情況下可能不可靠。 – MaD

+0

不給行動屬性它的價值,根據你的條件分配它在點擊提交按鈕,這就是它 – rahulsm

+1

電子郵件驗證的東西是**客戶端** JavaScript。表單動作是提交數據以供處理**服務器端**的URL。使用動作來運行該JavaScript沒有意義。去了解一下'addEventListener'函數和'submit'事件。 – Quentin

回答

2

達到你想要的東西,同時保持它儘可能靠近你有什麼,你可以這樣做:

function validateForm() { 
 
    var x = document.forms["myform"]["f1"].value; //changed to "myform" and "f1" 
 
    var atpos = x.indexOf("@"); 
 
    var dotpos = x.lastIndexOf("."); 
 
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { 
 
     alert("Not a valid e-mail address"); 
 
     return false; 
 
    } 
 
}
<form name="myform" class="login" action="getinfo.php" method="POST" onsubmit="return validateForm()"> <!--onsubmit handler added here --> 
 
    <input name="f1" type="text" placeholder="email" autofocus/> 
 
    <input name="f2" type="password" placeholder="example2"/> 
 
    <input type="submit"> <!--submit button was missing --> 
 
</form>

注意,重要的部分是,當你提交運行提交處理程序如果您希望提交表單,則返回true;否則返回false,您沒有。

它也建議在服務器端進行驗證,否則任何用戶可能會禁用JavaScript並繞過驗證。 請注意,將電子郵件輸入的類型更改爲電子郵件已強制瀏覽器本身進行驗證。

+0

非常感謝。我可以使用按鈕標記,而不是輸入類型=提交? –

+0

是的,用你想要的名稱添加一個值屬性('')。我沒有給它起名,所以它默認提交。 – Isac

+0

非常感謝你救了我 –