簡體   English   中英

如果表單為空,則阻止表單提交

[英]Prevent form from submitting if form is empty

在我的 HTML 表單中,我想使用一個按鈕來提交表單而不是輸入類型提交。 如果電子郵件為空,我有一個 javascript 代碼會出錯,也可以防止表單提交。 但是,代碼似乎不起作用,我收到此錯誤:無法獲取/提交

 const email = document.getElementById('email'); const form = document.getElementById('form'); const emailMessage = document.getElementById('email-message'); form.addEventListener('submit', e => { if (email.value === '' || email.value === null) { emailMessage.innerHTML = 'where is the email'; e.preventDefault(); } else { return true; } });
 <form id="form" action="submit"> <input id="email" type="email" /> <button type="submit">Go</button> <p id="email-message"></p> </form>

為什么不直接使用required屬性? 不需要JS

<input id="email" type="email" required>

這將檢查電子郵件字段是否不為空,並且另外輸入的字符串是否是有效的電子郵件格式。

請注意,HTML“必需”在版本低於 Safari 10.1(2017 年 5 月)的 Safari 瀏覽器中不起作用

編輯:要顯示自定義消息,請訂閱invalid事件

const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
   if (email.value == '')
     email.setCustomValidity('Where is the email?'); 
   else if (email.validity.typeMismatch)
     email.setCustomValidity('Email address be invalid!'); 
});

您可以在 Mozilla了解有關表單驗證的更多信息

你的代碼工作正常。 嘗試這個

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form id="form" action="submit">
    <input id="email" type="email"/>
    <button type="submit">Go</button>
    <p id="email-message"></p>
</form>

<script>
    const email        = document.getElementById('email');
    const form         = document.getElementById('form');
    const emailMessage = document.getElementById('email-message');

    form.addEventListener('submit', e => {
        if (email.value === '' || email.value === null) {
            emailMessage.innerHTML = 'where is the email';
            e.preventDefault();
        } else {
            return true;
        }
    });
</script>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM