[英]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!');
});
你的代碼工作正常。 嘗試這個
<!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.