Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ required ของ HTML DOM Input Email

คุณสมบัติ required ของ HTML DOM Input Email ใช้สำหรับกำหนดหรือตรวจสอบว่าช่องกรอกอีเมล (email) เป็นฟิลด์ที่บังคับต้องกรอกก่อนส่งฟอร์มหรือไม่

ไวยากรณ์ (Syntax)

การดึงค่า (คืนค่า boolean true/false)

inputEmailObject.required

การกำหนดค่า required

inputEmailObject.required = booleanValue

ค่า Boolean (Boolean Values)

booleanValueรายละเอียด
trueบังคับให้กรอกช่อง email ก่อนส่งฟอร์ม
falseไม่บังคับให้กรอก (ค่าเริ่มต้น)

ตัวอย่างการใช้งาน

ตัวอย่างด้านล่างแสดงฟอร์มส่งอีเมลที่บังคับให้กรอกอีเมลก่อนส่ง:

<!DOCTYPE html>
<html>
<head>
<title>Input Email required</title>
<style>
  form { width:70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; margin:5px; }
  input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
  <h1>Compose Mail</h1>
  <fieldset>
    <legend>Email-required</legend>
    <label for="EmailSelect">Email Id : <input type="email" id="EmailSelect" required> </label><br>
    <label for="textarea">Message : <textarea id="textarea" rows="2" cols="20" name="message" placeholder="Type message..."></textarea></label><br>
    <input type="button" onclick="showMessage()" value="Send Mail">
    <div id="divDisplay"></div>
  </fieldset>
</form>
<script>
  var divDisplay = document.getElementById("divDisplay");
  var inputEmail = document.getElementById("EmailSelect");
  function showMessage() {
    if(inputEmail.required === true && inputEmail.value === '')
      divDisplay.textContent = 'Cannot Send Mail: Email Id Required';
    else
      divDisplay.textContent = 'Mail Sent';
  }
</script>
</body>
</html>

ผลลัพธ์ (Output)

คลิกปุ่ม Send Mail โดยไม่กรอกอีเมล: แสดง "Cannot Send Mail: Email Id Required" หลังกรอกอีเมลแล้วคลิกอีกครั้ง: แสดง "Mail Sent"

การตรวจสอบรูปแบบ: type="email" จะตรวจสอบรูปแบบอีเมลอัตโนมัติ (ต้องมี @ และโดเมน)