คุณสมบัติ required ของ HTML DOM Input URL ใช้กำหนดหรือตรวจสอบว่าช่องป้อน URL จำเป็นต้องกรอกก่อนส่งฟอร์มหรือไม่
ไวยากรณ์ (Syntax)
การดึงค่า required
inputURLObject.required
การกำหนดค่า required
inputURLObject.required = booleanValue
ค่าบูลีน (Boolean Values)
| booleanValue | รายละเอียด |
|---|---|
| True | บังคับกรอก URL ก่อนส่งฟอร์ม |
| False | ค่าเริ่มต้น - ไม่บังคับกรอก |
ตัวอย่างการใช้งาน
ตัวอย่างตรวจสอบ URL ก่อน redirect
<!DOCTYPE html>
<html>
<head>
<title>Input URL 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>
<fieldset>
<legend>URL-required</legend>
<label for="URLSelect">URL: <input type="url" id="URLSelect" required> </label><br>
<input type="button" onclick="showMessage()" value="Go">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var inputURL = document.getElementById("URLSelect");
function showMessage() {
if(inputURL.required === true && inputURL.value === '')
divDisplay.textContent = 'Cannot Redirect: URL is Required';
else
divDisplay.textContent = 'Redirecting...';
}
</script>
</body>
</html>
ผลลัพธ์
คลิก "Go" โดยไม่กรอก URL - แสดง "Cannot Redirect: URL is Required"
กรอก URL แล้วคลิก "Go" - แสดง "Redirecting..."
การตรวจสอบเบราว์เซอร์: required ทำงานร่วมกับ type="url" จะตรวจสอบทั้งว่ามีค่า และรูปแบบ URL ถูกต้อง