Web Programming Reference

HTML · CSS · JavaScript · Regular Expression

224 topics

Reference scope: Lab 1–9(HTML、CSS、JavaScript)。Lab 7–9 新增 JavaScript Basics、Event-driven Programming 同 Client-side Form Validation;補充例子、教材不明確之處及拼寫修正已標明。Regular Expression 部分另外收錄常見格式練習。

HTML

知識點 / Topic內容 / Syntax & Example
HTML document structure
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My Web Page</title>
</head>
<body>
  Hello world!
</body>
</html>
Lab 1:head 放文件資訊;title 顯示於 browser tab;body 放頁面內容。DOCTYPE 同 charset 係現代 HTML 補充。
Heading / h1–h6
<h1>Main heading</h1>
<h2>Section heading</h2>
<h3>Subheading</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
Lab 1、4:h1 至 h6 係有效 heading;h7 唔係標準 heading。
Paragraph / line break / horizontal rule
<p>First paragraph.</p>
<p>Line one<br />Line two</p>
<hr />
Lab 1:p 段落、br 換行、hr 主題分隔線。
Whitespace / non-breaking space
Hello     world
Hello&nbsp;&nbsp;world
<pre>Line 1
    Line 2</pre>
Lab 1、3:普通空格同換行通常會合併;nbsp 保留不斷行空格;pre 係補充例子。
Heading alignment (legacy HTML)
Example 1
<h1 align="center">Title</h1>
Example 2
<h3 align="right">Subtitle</h3>
Example 3
<h1 style="text-align: center;">Title</h1>
Lab 1 使用舊式 align;現代 HTML 建議用 CSS。
Hyperlink / href
<a href="https://www.vtc.edu.hk/">VTC</a>
<a href="about.html">About</a>
<a href="#contact">Contact</a>
<h2 id="contact">Contact</h2>
Lab 1、2、4:href 指向網址;相對路徑同頁內連結係補充例子。
Email hyperlink / mailto
<a href="mailto:[email protected]">VTC Office</a>
Lab 1、2:開啟預設 email 程式。
Image as hyperlink
<a href="https://www.vtc.edu.hk/">
  <img src="photo.jpg" alt="VTC">
</a>
Lab 2:將 img 放喺 a 入面,圖片可以點擊。
Unordered list / ul / li
<ul>
  <li>Apple</li>
  <li>Banana</li>
</ul>
<ul style="list-style-type: square;">
  <li>Item</li>
</ul>
Lab 2:bullet list;disc、circle、square。教材舊寫法係 <ul type="square">。
Ordered list / ol / li
<ol type="I">
  <li>First</li>
  <li>Second</li>
</ol>
Lab 2:有次序列表;type 可用 1、I、i、A、a。
Definition list / dl / dt / dd
<dl>
  <dt>HTML</dt>
  <dd>HyperText Markup Language</dd>
</dl>
Lab 2 提及 Definition List,但冇提供程式碼;呢個係補充例子。
Table / tr / td / th
<table border="4">
  <tr><th>Fruit</th><th>Price</th></tr>
  <tr><td>Apple</td><td>10</td></tr>
  <tr><td>Orange</td><td>12</td></tr>
</table>
Lab 2:tr 係 row,td 係 data cell;th 係補充嘅 header cell。border attribute 屬舊式寫法。
Table width / height / cell width (legacy)
<table border="4" width="50%" height="100%">
  <tr>
    <td width="25%">Apple</td>
    <td width="75%">Banana</td>
  </tr>
</table>
Lab 2:教材舊式 table dimensions;現代用 CSS width、height,百分比高度要視乎 containing block。
Table cell alignment / valign (legacy)
Example 1
<td align="center">Centered</td>
Example 2
<td align="right">Right</td>
Example 3
<td valign="top">Top</td>
Example 4
<td valign="middle">Middle</td>
Example 5
<td style="text-align: center; vertical-align: top;">Text</td>
Lab 2:水平 align;垂直 valign。現代用 text-align 同 vertical-align。
Table colspan / merge columns
<table border="1">
  <tr><td colspan="2">Title</td></tr>
  <tr><td>A</td><td>B</td></tr>
</table>
Lab 2:colspan="2" 橫跨兩欄;同一行唔需要再加被合併嘅 cell。
Table rowspan / merge rows
<table border="1">
  <tr><td rowspan="2">A</td><td>B</td></tr>
  <tr><td>C</td></tr>
</table>
Lab 2:rowspan="2" 垂直跨兩行;第二行省略已被佔用嘅 cell。
Image inside table cell
<table border="1">
  <tr><td><img src="photo.jpg" alt="Photo"></td><td>Description</td></tr>
</table>
Lab 2:td 可以包含圖片或連結。
Iframe / embedded page
<iframe src="content.html" title="Content" width="400" height="250"></iframe>
Lab 2:將另一個 HTML page 嵌入目前網頁。
Two iframe layout / menu and content
Main page
<table style="width: 100%;">
  <tr>
    <td style="width: 20%;">
      <iframe src="add_ex2_menu.html" title="Menu" style="width: 100%; height: 300px;"></iframe>
    </td>
    <td style="width: 80%;">
      <iframe src="add_ex2_main.html" name="main" title="Content" style="width: 100%; height: 300px;"></iframe>
    </td>
  </tr>
</table>
Menu page
<a href="about.html" target="main">About</a>
Lab 2 Additional Exercise:20% menu、80% content;高度同 target 連動係補充例子。
Audio / music
<audio controls>
  <source src="music.mp3" type="audio/mpeg">
</audio>
Lab 2 learning outcome 提及 music,但未有具體程式碼;呢個係補充例子,需要媒體檔案。
Video
<video width="320" controls>
  <source src="movie.mp4" type="video/mp4">
</video>
Lab 2 learning outcome 提及 video;補充例子,需要媒體檔案。
Strong / emphasis
<strong>Important</strong>
<em>Emphasized text</em>
Lab 4 明確要求 strong;em 係補充。
Hidden input
<input type="hidden" name="region" value="Asia">
Lab 3(b):已確認 region 預設值係 Asia;hidden 唔顯示,但會提交。唔可以用 hidden 保護敏感資料。
Telephone input / tel
<input type="tel" name="phoneno" maxlength="8" pattern="[0-9]{1,8}">
Lab 3(d):最多 8 位數字(唔係必須剛好 8 位);maxlength 限制長度,pattern 驗證數字。要必填另加 required;tel 本身唔會限制數字。
Range input / slider
<input type="range" name="rating" min="1" max="5" step="1" value="3">
額外參考:range 同 number 都支援 min/max/step,但 Lab 3(k) 目標圖係數字輸入框,應使用 type="number"。
Date range / start and end dates
From <input type="date" name="startdate">
To <input type="date" name="enddate">
Lab 3(g):兩個 type="date",唔需要檢查開始日期是否早過結束日期。欄位 name 可按題目設定。
Separate checkbox names
<input type="checkbox" name="F1" value="G" checked>Gym
<input type="checkbox" name="F2" value="S">Swimming Pool
<input type="checkbox" name="F3" value="B">Business Centre
Lab 3(h):三個獨立選項,Gym 預設選中。未選嘅 checkbox 通常唔會提交。
Single select / option
<select name="room">
  <option value="D">Double</option>
  <option value="T">Twin</option>
  <option value="S" selected>Single</option>
</select>
Lab 3(f):Single 預設選中;加入 multiple 就可以選擇多項。
Form / GET / POST
<form action="/submit" method="post">
  ...
</form>
action 指定提交位置;method 指定提交方式。
File upload
<form method="post" enctype="multipart/form-data">
  <input type="file" name="photo">
</form>
真正上傳檔案時使用 multipart/form-data。
Number input
<input type="number" name="quantity" min="1" max="10" step="1">
min / max 限制數值範圍;step 控制間距。
Required field
<input type="text" name="username" required>
唔可以留空。
Radio buttons
<input type="radio" name="level" value="A" checked> A
<input type="radio" name="level" value="B"> B
相同 name 屬於同一組;checked 指定預設選項。
Checkbox
<input type="checkbox" name="extras" value="A" checked> A
可以獨立選擇或取消。
Select / multiple / optgroup
<select name="items" multiple size="4">
  <optgroup label="Group A">
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
  </optgroup>
</select>
multiple 容許選擇多項;size 控制可見列數。
Textarea
<textarea name="comments" rows="4" cols="30">Default text</textarea>
多行文字輸入;初始文字放喺開始同結束標籤之間。
Submit / Reset / Button
Example 1
<input type="submit" value="Submit">
Example 2
<input type="reset" value="Reset">
Example 3
<input type="button" value="Click">
reset 恢復初始值;button 本身唔會提交表單。
Image
<img src="photo.png" alt="Photo" width="60">
src 指定相對或絕對圖片路徑。
Pattern / character length
Example 1
<input type="text" pattern=".{6}" required>
Example 2
<input type="text" minlength="6" maxlength="6">
pattern=".{6}" 要求剛好六個字元(一般單行文字);required 防止留空。
Date / Color
Example 1
<input type="date" name="day">
Example 2
<input type="color" name="color">
使用瀏覽器內置選擇器。
Output / oninput
<input type="number" oninput="document.getElementById('result').value = this.value * 50">
<output id="result">0</output>
輸入時更新計算結果。50 係例子單價。
Submit event
<form name="f1" onsubmit="return check_form();">
  ...
</form>
function 回傳 false 就取消正常提交。
Default value / value
<input type="number" name="qty" value="1">
value 設定初始值;reset 會回復初始值。
Placeholder
<input type="text" placeholder="Enter your name">
提示文字唔等於輸入值。
Disabled / readonly
Example 1
<input name="a" disabled>
Example 2
<input name="b" readonly>
disabled 唔可以操作,亦唔會提交;readonly 仍可提交。
File type / accept
<input type="file" name="photo" accept="image/*">
限制檔案選擇器建議嘅類型;唔代替伺服器驗證。
Fieldset / Legend
<fieldset>
  <legend>Personal Details</legend>
  <input name="username">
</fieldset>
fieldset 將相關欄位分組;legend 係組別標題。
Default selected option
<select name="city">
  <option value="A" selected>City A</option>
  <option value="B">City B</option>
</select>
selected 指定預設選項。
Numeric / alphabetic pattern
Example 1
<input type="text" pattern="[0-9]{6}" required>
Example 2
<input type="text" pattern="[A-Za-z]{6}">
Example 3
<input type="text" pattern="[A-Za-z0-9]{6}">
分別限制六個數字、英文字母、英文字母或數字;按要求選用。
Named output / form oninput
<form oninput="result.value = qty.value * 50">
  <input type="number" name="qty" id="qty" value="0">
  <output name="result" for="qty">0</output>
</form>
可喺 form 上使用 oninput;output 嘅 for 引用相關 input ID。
Label / id / name
<label for="email">Email:</label>
<input type="email" id="email" name="email">
for 對應 id;name 用於表單提交及 JavaScript 取值。
External CSS / JavaScript
Example 1
<link rel="stylesheet" href="style.css">
Example 2
<script src="script.js" defer></script>
連接外部文件;defer 令 script 喺 HTML 解析完成後執行。
POST / multipart form / HTTPS
<form method="post" enctype="multipart/form-data">
  <input type="file" name="photo">
  <input type="submit" value="Send Data">
</form>
Lab 3(a)(j)(m):POST 配合 multipart/form-data 上傳檔案。教材稱 secure submission,但 POST 本身唔會加密;傳輸安全依賴 HTTPS。題目冇指定 action。
Radio group / default booking option
<input type="radio" name="booking" value="I" checked>Internet
<input type="radio" name="booking" value="A">Agency
Lab 3(e):相同 name、不同 value;Internet 預設選中。booking 係自訂欄位名稱。
Textarea dimensions / initial text
<textarea name="comment" cols="50" rows="4">In less 200 words...</textarea>
Lab 3(i):50 字元闊、4 行高,文字係初始值而唔係 placeholder。rows/cols 唔限制最大字數。
Integer number range / rating
<input type="number" name="rating" min="1" max="5" step="1">
Lab 3(k):整數 1–5,step 預設為 1;如果需要必填先加 required。
Color picker / reset to defaults
<input type="color" name="colour">
<input type="submit" value="Send Data">
<input type="reset" value="Clear Data">
Lab 3(l–n):color picker;reset 恢復初始值(唔一定清空)。教材未指定 colour 嘅初始值;name 係自訂。
Named iframe / link target
<a href="pageA.html" target="content">
  <img src="images/A.gif" alt="A">
</a>
<iframe name="content" src="pageA.html" title="Content"></iframe>
Lab 5 Q2:target 對應 iframe 嘅 name,點擊連結只更新 iframe。HTML5 iframe 要有結束標籤;教材 frameborder 屬舊式語法。
Nested list / submenu
<ul>
  <li><a href="#">Menu</a>
    <ul class="sub">
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
    </ul>
  </li>
</ul>
Lab 5 Q1:submenu 嘅 ul 放喺父 li 入面;可以配合 hover 顯示。
Password input / retype
<input type="password" id="pwd">
<input type="password" id="retype">
Lab 8 Q1:password 遮住顯示文字,但唔代表加密;用 id 配合 JavaScript 比較。
Pattern / capital first character
<input type="text" name="name" pattern="[A-Z].*"
       title="Capital first character" required>
Lab 9(a):首字元為 A–Z,之後可以有其他字元。pattern 驗證整個值;required 防止留空。
Number / minimum age
<input type="number" name="age" min="18" required>
Lab 9(b):最小值 18,number 預設 step 為 1。
URL input / valid URL
<input type="url" name="url" required
       title="http://domainName">
Lab 9(c):瀏覽器檢查 URL 格式,唔會驗證網站是否存在,亦唔只限 HTTP。title 只係提示。
Pattern / time HH:MM:SS
<input type="text" name="time" required
       pattern="([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"
       title="HH:MM:SS">
Lab 9(d):24 小時制,00:00:00–23:59:59。若只要求外觀格式,可用 [0-9]{2}:[0-9]{2}:[0-9]{2},但唔會檢查有效時間。
Pattern / hexadecimal color code
<input type="text" name="color" required
       pattern="#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})"
       title="#hhh or #hhhhhh">
Lab 9(e):#abc、#12ABef 合法;#abcd、#ggg 唔合法。| 代表 OR。
Radio group / required selection
<input type="radio" name="gender" value="M" required> Male
<input type="radio" name="gender" value="F"> Female
Lab 9:同名 radio group 只要其中一個有 required,就要求選擇其中一項。
Checkbox group / same name
<input type="checkbox" name="subjects" value="eng"> English
<input type="checkbox" name="subjects" value="math"> Mathematics
Lab 9:同名 checkbox 可以獨立選擇多項;JavaScript 用 collection 同 .checked 逐項處理。
Select / empty placeholder option
<select name="sport">
  <option value="">Please select one sport</option>
  <option value="fb">Football</option>
  <option value="sw">Swimming</option>
</select>
Lab 9:預設 option value 為空字串。若題目要求必須選擇,可額外在 select 加 required。
Validation hint / title
<input type="text" pattern="[0-9]{6}" title="Enter 6 digits" required>
補充:title 提供格式提示,實際錯誤訊息因瀏覽器而異。
Disable native validation / novalidate
<form novalidate>
  <input name="email" type="email" required>
  <input type="submit" value="Submit">
</form>
補充:novalidate 跳過提交時嘅原生驗證;唔代表欄位限制被刪除。只喺需要自訂驗證時使用。

CSS

知識點 / Topic內容 / Syntax & Example
Inline CSS / local style sheet
<p style="background-color: red; color: pink;">Paragraph</p>
<h1 style="font-size: 15pt;">Heading</h1>
Lab 4 Q1:style attribute 只套用於指定元素。heading 唔應放入 p,瀏覽器會自動結束 p。
Internal CSS / global style sheet
<head>
  <style type="text/css">
    body { background-color: pink; }
    p { color: blue; background-color: green; }
    h1 { font-size: 25px; }
    h2 { color: yellow; font-size: 20px; }
  </style>
</head>
Lab 4 Q2:style element 放喺 head,套用到符合 selector 嘅元素。
External CSS / linked style sheet
HTML head
<link rel="stylesheet" href="style.css" type="text/css">
style.css
body { font-size: 10px; background-color: yellow; }
p { font-size: 20px; }
h1 { font-size: 30px; font-weight: bold; color: red; }
Lab 4 Q3:HTML 同 CSS 分開保存;href 必須同實際 CSS 文件名相符。
Element selector / type selector
body { background-color: yellow; font-size: 15px; }
strong { font-size: 20px; color: red; font-weight: bold; }
Lab 4 Q4 稱為 contextual selector;實際呢兩個規則係 element/type selector。
Grouping selector / comma
h1, h2 { color: blue; }
h2 { font-weight: bold; }
Lab 4 Q3:逗號代表分別選中 h1 同 h2。
Contextual / descendant selector
p strong { color: red; }
nav a { text-decoration: none; }
補充 Lab 4 selector 概念:空格代表 descendant;只選擇指定 ancestor 入面嘅元素。
Class selector / dot
CSS
.first { background-color: green; }
.second { background-color: red; color: blue; }
.third { background-color: pink; color: yellow; }
HTML
<p class="first">First</p>
<p class="second">Second</p>
<p class="third">Third</p>
Lab 4 Q5:class selector 用 .;同一個 class 可以重複使用。CSS 同 HTML 分別放入相應位置。
ID selector / hash
CSS
#first { background-color: green; }
#second { background-color: red; color: blue; }
#third { background-color: pink; color: yellow; }
HTML
<p id="first">First</p>
<p id="second">Second</p>
<p id="third">Third</p>
Lab 4 Q6:ID selector 用 #;同一頁嘅 ID 應該唯一。
Font size units / px / pt / percent
h1 { font-size: 40pt; }
p { font-size: 20px; }
strong { font-size: 150%; }
Lab 4 使用 px、pt、%;1pt = 4/3 CSS px;百分比 font-size 相對父元素字體大小。
Font family / fallback fonts
body {
  font-family: Arial, "Arial Black", Verdana, sans-serif;
  background-color: grey;
  color: white;
}
h1, h2 { color: blue; }
h1 { font-size: 40pt; }
strong { color: yellow; }
Lab 4 Q7b:按順序揀可用字體;sans-serif 係補充 fallback。
Hyperlink underline / text-decoration
a { text-decoration: none; }
a:hover { text-decoration: underline; }
Lab 4 Q7c:預設冇底線,mouse hover 時顯示底線。
Pseudo-element / first-letter / drop caps
Lab syntax
p:first-letter { font-size: 300%; }
Modern CSS
p::first-letter { font-size: 300%; }
Lab 4 Q7c:每段首字放大至正常字體三倍;兩種 selector 寫法都適用。
List style type
ul { list-style-type: square; }
ol { list-style-type: upper-roman; }
Lab 2 舊式 ul type 嘅現代 CSS 寫法;disc、circle、square、decimal、upper-roman 等。
Table borders / collapse / spacing
table { border-collapse: collapse; width: 50%; }
th, td { border: 1px solid black; padding: 8px; }
Lab 2 table border 嘅現代 CSS 補充;collapse 合併相鄰 border。
Table vertical alignment
td { text-align: center; vertical-align: middle; }
Lab 2 align / valign 嘅現代 CSS 補充。
CSS cascade / specificity / inheritance
p { color: blue; }
.note { color: green; }
#intro { color: red; }
補充概念:同一來源、層級、重要性下,ID > class > element;相同 specificity 通常後面規則優先。普通 inline style 通常優先於普通 selector 規則。color 可繼承,background-color 通常唔會。
Flex container / wrapping
.container {
  display: flex;
  flex-flow: row wrap;
}
水平方向排列,空間不足時容許換行。
Flex direction / alignment
.container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
justify-content:主軸;align-items:交叉軸。
Flex item / order / grow / shrink
.item {
  order: 2;
  flex-grow: 3;
  flex-shrink: 0;
}
order 控制排序;grow 分配剩餘空間;shrink: 0 防止縮細。
Full width / fixed width
.wide { width: 100%; }
.sidebar { width: 150px; }
百分比或固定像素闊度;padding、border 同 margin 會影響實際佔用空間。
Display / visibility
.hidden { display: none; }
.image { display: block; }
.inline { display: inline-block; }
display: none 隱藏元素而且唔保留排版空間。
Font / text alignment
.content {
  font-size: large;
  text-align: justify;
}
font-size 設定字體大小;justify 左右對齊。
Multiple columns
.article {
  column-count: 2;
  column-gap: 20px;
  column-rule: 1px solid black;
}
.article h2 { column-span: all; }
分欄、欄距、分隔線;標題橫跨所有欄。
Float / clear
img { float: left; margin-right: 10px; }
.next { clear: both; }
float: left / right 令文字環繞圖片;clear: both 避開兩邊浮動元素;clear: none 唔限制。
Media query
@media only screen and (max-width: 850px) {
  .sidebar { width: 100%; }
  .menu { display: flex; }
  .label { display: none; }
  .article { column-count: 1; }
}
當 viewport 闊度 ≤ 850px 時套用;min-width 則係大於或等於。
Selectors
#header { color: blue; }
.label { font-weight: bold; }
#nav img { display: block; }
input[name="quantity"] { width: 50px; }
ID、class、descendant 同 attribute selectors。
Text alignment
Example 1
text-align: left;
Example 2
text-align: center;
Example 3
text-align: right;
Example 4
text-align: justify;
四種替代寫法;按要求選其中一個。
Flex direction / wrap alternatives
Option A
flex-direction: column;
flex-wrap: wrap;
Option B
flex-flow: column wrap;
column 垂直排列;row 水平排列。
Justify content
Example 1
justify-content: flex-start;
Example 2
justify-content: center;
Example 3
justify-content: flex-end;
Example 4
justify-content: space-between;
Example 5
justify-content: space-around;
Example 6
justify-content: space-evenly;
主軸對齊替代值;space-between 兩端無額外空隙,around 每項兩側有空隙,evenly 所有空隙相等。
Align items / align self
.container { display: flex; align-items: center; }
.item { align-self: flex-start; }
交叉軸對齊;align-self 覆蓋個別 flex item 嘅對齊。
Margin
Example 1
margin: 5px;
Example 2
margin: 0 auto;
Example 3
margin: 0 0 3px 0;
外邊距;四值順序 top right bottom left;auto 可配合固定闊度水平置中。
Padding
Example 1
padding: 10px;
Example 2
padding: 10px 15px;
內邊距;兩值順序上下、左右。
Border / radius
border: 1px solid black;
border-radius: 10px;
邊框闊度、樣式、顏色;radius 設定圓角。
Box shadow / box sizing
box-shadow: 5px 5px 5px #888888;
box-sizing: border-box;
陰影水平、垂直偏移及模糊;border-box 將 padding 同 border 包含喺指定闊度。
Background color / color
background-color: lightblue;
color: black;
背景顏色同文字顏色。
Font family / weight / style
font-family: Georgia, serif;
font-weight: bold;
font-style: italic;
字體、粗體、斜體。
Responsive order / flex basis
@media (max-width: 700px) {
  .sidebar { order: 3; flex-basis: 100%; }
  .content { order: 2; flex-basis: 100%; }
}
改變 flex items 嘅排列次序同基準尺寸;前提係 parent 已啟用 flex。
Image size / responsive image
img {
  width: 100px;
  max-width: 100%;
  height: auto;
}
保持圖片比例,避免超出容器。
Visibility / display alternatives
.hidden { visibility: hidden; }
.removed { display: none; }
.inline { display: inline; }
visibility:hidden 保留空間;display:none 唔保留;inline 行內顯示。
Responsive flex / float reset
@media (max-width: 700px) {
  .menu { display: flex; flex-wrap: wrap; gap: 10px; }
  .menu img { margin: 0; }
  .sidebar img { float: none; }
  .sidebar p { clear: both; }
}
細畫面可改水平選單、取消 float 或令文字移到圖片下面;按要求選用。
List reset / inline-block menu
.menu ul {
  list-style: none;
  margin: 0;
  padding: 0;
  width: 150px;
  background-color: darkgreen;
  text-shadow: 2px 2px 2px red;
  border-radius: 10px;
  display: inline-block;
}
Lab 5 Q1(a):移除 bullets 同預設間距;inline-block 可橫向排列同設定尺寸。
Block links / padding / line-height
.menu a {
  text-decoration: none;
  padding: 10px 20px;
  line-height: 1.2em;
  color: white;
  display: block;
}
Lab 5 Q1(b):令連結佔一整行;padding 兩值依次係上下、左右。
Text shadow / box shadow
text-shadow: 2px 2px 2px red;
box-shadow: 10px 10px 5px grey;
Lab 5 Q1(a)(d):水平偏移、垂直偏移、blur radius、顏色;text-shadow 套用文字,box-shadow 套用元素盒。
Nested hover / selector specificity
.menu a:hover {
  background-color: lightgreen;
  color: black;
}
.menu .sub a:hover {
  background-color: lightblue;
}
Lab 5 Q1(c)(e):較具體嘅 submenu selector 可覆蓋背景色。
Position / relative and absolute
.menu > ul > li { position: relative; }
.menu .sub {
  position: absolute;
  top: 38px;
  left: 0;
  background-color: darkblue;
  box-shadow: 10px 10px 5px grey;
  transform: rotate(-10deg);
}
Lab 5 Q1(d):top 需要非 static positioning 先有效;relative parent 同 absolute submenu 係可行實現示例,唔係教材指定唯一寫法。
Overflow / clipping / scrolling
Option A
overflow: hidden;
Option B
overflow: auto;
Lab 5 Q1(f)、Q2(b):hidden 裁剪超出範圍嘅內容;auto 有需要時先出現 scrollbar。
Transition / animated submenu
.menu .sub li {
  overflow: hidden;
  height: 0;
  transition: height 500ms;
}
.menu li:hover .sub li {
  height: 40px;
}
Lab 5 Q1(f)(g):hover 父項目時逐步展開 submenu;500ms = 0.5 秒。使用 height 由 0 到固定值可以做 transition。
Transform / translate / rotate
Option A
transform: translate(50px, 150px);
Option B
transform: rotate(-10deg);
Lab 5 Q1(d)、Q2(b):translate 移動元素相對原本位置;rotate 負角度逆時針。兩個 transform declaration 會覆蓋,要組合就放同一行。
Transform / scale / skewY
img:hover {
  transform: scale(1.5) skewY(20deg);
}
Lab 5 Q2(c):放大 1.5 倍同 Y 方向傾斜 20 度;組合 transform 時順序會影響結果。
Absolute positioning + translate coordinates
.canvas { position: relative; }
.canvas .item {
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(120px, 80px);
}
Lab 5 Q2(b) 通用示例:先將元素原點統一至容器左上角,再 translate(x,y)。如果直接對普通 flow 元素使用 translate,要扣除原來位置;120/80 係獨立例子。
Stacking order / z-index
.item { position: absolute; z-index: 2; }
.item:hover { z-index: 3; }
補充 Lab 5 重疊圖片概念:z-index 控制同一 stacking context 入面嘅疊放次序。
Flex layout / desktop structure
#flex-container { display: flex; flex-flow: row wrap; }
#header, #nav, #main, #aside, #footer {
  background: #DDF;
  border: 1px solid black;
  border-radius: 8px;
  margin: 5px; padding: 15px;
}
#header { order: 1; width: 100%; height: auto; }
#nav { order: 2; width: 200px; }
#main { order: 3; width: 10px; height: auto; flex-grow: 1; background: #FCC; }
#aside { order: 4; width: 200px; }
#footer { order: 5; width: 100%; height: 50px; }
Lab 6(a–d)(g):五區域布局;header/footer 獨立一行,main 分配剩餘空間。grow 分配正數剩餘空間,縮小係 flex-shrink 負責。
Responsive breakpoints / cascade / order
@media only screen and (max-width: 1000px) {
  #nav { order: 4; width: 100px; }
  #main { background: #CFC; }
  #aside { order: 2; width: 100px; }
}
@media only screen and (max-width: 800px) {
  #nav { order: 4; width: 100%; }
  #nav ul { list-style: none; display: flex;
    flex-direction: row; justify-content: space-around; }
  #main { background: #FFC; }
  #aside { display: none; }
}
Lab 6(h)(j):1000px 以下 nav/aside 對調;800px 以下 nav 全闊、水平選單、隱藏 aside。兩條 query 喺 800px 都成立,較後同等 specificity 規則覆蓋。教材 flow-direction 係拼寫錯誤,正確係 flex-direction。
Float image / margin-right / clear
#header img { float: left; margin-right: 10px; }
#header div { clear: none; }
Lab 6(f):圖片浮向左,文字繞圖;margin-right 增加圖文距離。clear:none 係預設。
Three columns / spanning heading / vendor prefix
#main {
  -webkit-column-count: 3;
  column-count: 3;
}
#main h1 {
  line-height: 0.2;
  -webkit-column-span: all;
  column-span: all;
}
Lab 6(l):教材用 -webkit- prefix;現代瀏覽器使用標準 column-count / column-span。line-height:0.2 係教材指定嘅極細行高,普通多行標題唔建議。Lab 6 三欄唔會因 media query 自動變一欄,除非另外設定。
Line height / unitless vs em
Option A
line-height: 1.2;
Option B
line-height: 1.2em;
Lab 5 Q1(b)、Lab 6(l):1.2em 係目前字體大小嘅 1.2 倍;無單位值可按後代元素自己嘅字體大小計算。
Responsive viewport / narrow main (supplement)
@media only screen and (max-width: 850px) {
  #main { column-count: 1; font-size: medium; }
  .label { display: none; }
  #nav { width: 100%; display: flex; flex-direction: row;
    justify-content: space-around; }
}
補充:窄畫面改單欄、隱藏文字標籤及水平選單;850px 係示例,唔係 Lab 6 嘅指定 breakpoint。按正式題目調整。

JavaScript

知識點 / Topic內容 / Syntax & Example
Get form / input value
Named form elements
let f = document.forms["f1"];
let quantity = f.elements["quantity"].value;
Alternative shorthand
let value = document.f1.quantity.value;
.value 一般回傳字串;用 Number(value) 轉成數字。
Get element by ID
let el = document.getElementById("result");
el.textContent = "Hello";
input / output 可使用 .value;普通 div / span 可使用 .textContent。
Radio / Checkbox checked
const level = document.f1.level;
if (level[0].checked) {
  alert("A");
} else if (level[1].checked) {
  alert("B");
} else {
  alert("Not selected");
}
兩個 radio 同 name="level",value 分別係 A、B。.checked 回傳 Boolean。若冇 required 或預設 checked,兩項都可能未選;唔可以直接當成 B。
Select options / length
let options = document.f1.items.options;
let total = options.length;
options 包含所有選項,而唔只係已選嘅選項。
For loop / selected
let count = 0;
for (let i = 0; i < options.length; i++) {
  if (options[i].selected) {
    count++;
  }
}
逐個檢查 option;.selected 回傳 Boolean。
String concatenation / newline
let msg = "Summary:\n";
msg = msg + count + " items selected\n";
alert(msg);
+ 組合字串;\n 代表換行;alert 顯示訊息。
Function / return false
function check_form() {
  alert("Checked");
  return false;
}
配合 onsubmit="return check_form();" 使用。
Event / calculation
function calculate() {
  let n = Number(document.getElementById("qty").value);
  document.getElementById("result").value = n * 50;
}
由 oninput="calculate()" 或 onchange="calculate()" 呼叫。
Form by ID / named elements
const f = document.getElementById("f1");
const value = f.elements["quantity"].value;
以 form ID 取得表單,再以欄位 name 取值。
Get elements by name
const radios = document.getElementsByName("level");
const checked = radios[0].checked;
取得同名元素集合;索引由 0 開始。
Number conversion
Number("12.5");     // 12.5
parseInt("12.5", 10); // 12
parseFloat("12.5");  // 12.5
input.value 係字串;數值運算前可轉換。
Radio group value
const level = document.f1.level.value;
同名 radio group 嘅 value 係已選選項嘅 value;未選通常係空字串。
Update text / HTML
element.textContent = msg;
// only for trusted HTML markup:
element.innerHTML = "<b>Done</b>";
純文字用 textContent;innerHTML 會解析 HTML,唔應直接插入未經處理嘅使用者輸入。
Confirm dialog
if (confirm("Continue?")) {
  alert("Confirmed");
}
confirm 回傳 true 或 false。
Selected index / selected options
const s = document.f1.items;
const index = s.selectedIndex;
const count = s.selectedOptions.length;
selectedIndex 係第一個已選索引,冇選係 -1;selectedOptions 包含所有已選項。
Events / event listener
JavaScript listener
document.getElementById("qty").addEventListener("input", calculate);
HTML alternative
<input id="qty" oninput="calculate()">
input 即時觸發;change 通常喺更改完成後觸發。
Complete form processing example
<form id="survey" onsubmit="return summarize();">
  <input type="number" name="score" required>
  <input type="radio" name="level" value="A" required> A
  <input type="radio" name="level" value="B"> B
  <select name="subjects" multiple>
    <option>Math</option>
    <option>Science</option>
  </select>
  <input type="submit" value="Submit">
</form>
<script>
function summarize() {
  const f = document.getElementById("survey");
  const options = f.elements["subjects"].options;
  let count = 0;
  for (let i = 0; i < options.length; i++) {
    if (options[i].selected) count++;
  }
  let msg = "Score: " + f.elements["score"].value + "\n";
  msg += "Level: " + f.elements["level"].value + "\n";
  msg += "Subjects: " + count;
  alert(msg);
  return false;
}
</script>
獨立 survey 例子,展示取得輸入值、radio value、for loop、selected、訊息及阻止提交。
Script / document.write / HTML markup
<script>
  document.write("<h1><b><i>Hello<br>JavaScript!</i></b></h1>");
</script>
Lab 7 Q1:document.write 可寫入 HTML;<br> 喺網頁換行。只喺頁面初始解析時使用,載入後可能覆蓋頁面。
Alert / window.alert / newline
window.alert("Hello\nJavaScript!");
Lab 7 Q1:alert 內用 \n 換行,唔係 <br>。window.alert() 同 alert() 一樣。
Button onclick / JavaScript pseudo-URL
<button type="button" onclick="showAlert()">Show Alert</button>
<a href="javascript:showAlert()">Show Alert</a>
<script>
function showAlert() {
  alert("Hello\nJavaScript!");
}
</script>
Lab 7 Q1(b):教材要求 event handler 同 pseudo-URL;一般網站較建議用 button 或事件監聽器。
Prompt / window.prompt / cancel
var name = window.prompt("What is your name?");
if (name !== null) {
  alert("Hi " + name);
}
Lab 7:prompt 回傳字串,Cancel 回傳 null;Cancel 檢查係補充。
Image onclick / function argument
<img src="one.png" alt="1" onclick="clicked(1)">
<img src="two.png" alt="2" onclick="clicked(2)">
<img src="three.png" alt="3" onclick="clicked(3)">
<script>
function clicked(n) {
  var name = prompt("What is your name?");
  if (name !== null) alert("Hi " + name + ", you clicked on " + n);
}
</script>
Lab 7 Q2:用同一 function 接收唔同參數;圖片檔名係示例,請換成實際檔名。
Function / parameter / return value
function multiply(a, b) {
  return a * b;
}
var result = multiply(3, 4);
Lab 7 Q3:function 可接收 parameter,return 將結果交返呼叫位置。
Math.PI / Math.pow / sphere volume
function sphereVolume(radius) {
  return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}
var r = parseFloat(prompt("Enter radius"));
if (!isNaN(r) && r >= 0) {
  alert(sphereVolume(r).toFixed(2));
}
Lab 7 Q3:球體體積;radius=3 顯示 113.10。輸入檢查係補充。
toFixed / decimal places
var value = 12.3456;
var text = value.toFixed(2); // "12.35"
Lab 7 / Lab 8:固定兩位小數,回傳字串;再做加法前要轉回 number。
String addition vs numeric addition
var x = "2";
var y = "3.5";
alert(x + y); // 23.5 (string)
var z = parseInt(x, 10) + parseFloat(y);
alert(z.toFixed(2)); // 5.50
Lab 7 Optional Q4:prompt 回傳字串;+ 可能係字串拼接。
isNaN / if else / numeric validation
var x = parseInt(prompt("Enter integer"), 10);
var y = parseFloat(prompt("Enter decimal"));
if (isNaN(x) || isNaN(y)) {
  alert("Invalid number");
} else {
  alert((x + y).toFixed(2));
}
Lab 7 Optional Q4(b):isNaN 判斷轉換結果;parseInt 會截斷小數,parseFloat 可接受數字開頭嘅字串。
do while / repeated prompt / getNum
function getNum() {
  var n;
  do {
    var text = prompt("Enter a number");
    if (text === null) return null;
    n = text.trim() === "" ? NaN : Number(text);
  } while (isNaN(n) || !isFinite(n));
  return n;
}
var x = getNum();
if (x !== null) {
  var y = getNum();
  if (y !== null) alert((x + y).toFixed(2));
}
Lab 7 Optional Q4(c):輸入唔合法就再次問;Cancel 可以退出(補充)。兩次輸入數字後相加。
Comparison / logical operators
a === b   // equal value and type
a !== b   // not equal
x >= 18   // greater than or equal
x < 10    // less than
A && B    // AND
A || B    // OR
!A        // NOT
Lab 7–9 通用補充:if 條件常用比較及邏輯運算;= 係 assignment,唔係比較。
Event handlers / onload onclick onchange oninput onkeyup onsubmit
<body onload="startform()">
<form onsubmit="return checkFields()">
  <select onchange="update()"><option>A</option><option>B</option></select>
  <input oninput="update()">
  <input onkeyup="update()">
  <button type="button" onclick="update()">Update</button>
</form>
Lab 7–8:onload 頁面載入完成;onclick 點擊;onchange 確認更改;oninput 即時輸入;onkeyup 放開鍵盤;onsubmit 提交。函數需自行定義。
Form validation / blank username / password match
function checkFields() {
  var user = document.getElementById("tfUser").value;
  var pwd = document.getElementById("tfPwd").value;
  var retype = document.getElementById("tfRPwd").value;
  if (user.trim() === "") {
    alert("Username cannot be blank");
    return false;
  }
  if (pwd !== retype) {
    alert("Passwords do not match");
    return false;
  }
  return true;
}
Lab 8 Q1:配合 <form onsubmit="return checkFields()">;false 阻止提交,true 容許提交。trim 額外防止純空白。
Disabled property / enable disable controls
var f = document.forms["order"];
f.elements["sub1"].disabled = true;
f.elements["shipping"][0].disabled = false;
Lab 8 Q2:true 停用,false 啟用。disabled 欄位唔會隨表單提交;readonly 則一般會。
Focus / focus()
document.forms["order"].elements["product"].focus();
Lab 8 Q2:將鍵盤焦點放到 product 選單。
Form reset / reset()
var f = document.forms["order"];
f.reset();
Lab 8 Q2:恢復表單初始值,但唔會自動恢復 JavaScript 更改過嘅 disabled 狀態。
Select selectedIndex / selected option value
var product = document.forms["order"].elements["product"];
var index = product.selectedIndex;
if (index >= 0) {
  var itemValue = product.options[index].value;
  var itemText = product.options[index].text;
}
Lab 8 Q2:selectedIndex 由 0 開始;.value 取得提交值;.text 取得畫面文字。
Loop / enable or disable radio group
var shipping = document.forms["order"].elements["shipping"];
for (var i = 0; i < shipping.length; i++) {
  shipping[i].disabled = true;
}
Lab 8 Q2:遍歷同名 radio group;改成 false 就重新啟用。
Order calculation / initialize and total price
function startform() {
  var f = document.forms["order"];
  f.sub1.disabled = true;
  f.sub2.disabled = true;
  f.total.disabled = true;
  for (var i = 0; i < f.shipping.length; i++) {
    f.shipping[i].disabled = true;
  }
  f.product.focus();
}
function total_price() {
  var f = document.forms["order"];
  var s1 = parseFloat(f.sub1.value);
  var s2 = parseFloat(f.sub2.value);
  f.total.value = (s1 + s2).toFixed(2);
}
Lab 8 Q2(ii–iii):使用教材 sub1、sub2、total 欄位;文字提及 tax,但模板冇稅率或獨立稅欄,因此例子只加商品小計及運費。
Order price / quantity / shipping callback
function order_price() {
  var f = document.forms["order"];
  var index = f.product.selectedIndex;
  if (index <= 0) {
    f.reset();
    startform();
    return;
  }
  var item_value = parseFloat(f.product.options[index].value);
  var qty_ordered = Number(f.qty.value);
  if (!Number.isInteger(qty_ordered) || qty_ordered < 0) qty_ordered = 0;
  f.sub1.value = (item_value * qty_ordered).toFixed(2);
  for (var i = 0; i < f.shipping.length; i++) {
    f.shipping[i].disabled = false;
  }
  total_price();
}
function shipping_price(field) {
  var f = document.forms["order"];
  f.sub2.value = parseFloat(f.shipping[field].value).toFixed(2);
  total_price();
}
Lab 8 Q2(iv–v):配合上面 startform()、total_price()。教材冇指定不合法 qty 嘅處理方式;例子用 0。
Order form / event wiring
<body onload="startform()">
<form name="order" onreset="setTimeout(startform, 0)">
  <select name="product" onchange="order_price()">
    <option value="0">Select an item</option>
    <option value="20.50">Item A</option>
    <option value="30.00">Item B</option>
  </select>
  <input name="qty" oninput="order_price()">
  <input name="sub1" value="0.00">
  <input type="radio" name="shipping" value="5.50" onclick="shipping_price(0)"> Standard
  <input type="radio" name="shipping" value="8.00" onclick="shipping_price(1)"> Express
  <input name="sub2" value="0.00">
  <input name="total" value="0.00">
  <input type="submit" value="Submit">
  <input type="reset" value="Reset">
</form>
Lab 8 Q2:配合上述四個函數。oninput 同 onclick 係可行寫法;onreset 延後恢復 disabled 係補充,唔係原題要求。
Named form / field value and name collision
var f = document.forms["f1"];
var name = f.elements["name"].value;
var age = f.elements["age"].value;
Lab 9(f):用 elements["name"] 避免與 form 自己嘅 name property 混淆;一般欄位亦可用 document.f1.age.value。
Radio group / loop and checked value
var radios = document.forms["f1"].elements["gender"];
var gender = "";
for (var i = 0; i < radios.length; i++) {
  if (radios[i].checked) {
    gender = radios[i].value;
    break;
  }
}
Lab 9(f):用 .checked 判斷,.value 取得 M 或 F。亦可直接用同名 radio group 嘅 .value。
Checkbox group / collect values / count
var boxes = document.forms["f1"].elements["dse"];
var values = [];
var count = 0;
for (var i = 0; i < boxes.length; i++) {
  if (boxes[i].checked) {
    values.push(boxes[i].value);
    count++;
  }
}
alert(values.join(", "));
Lab 9(f):同名 checkbox 用 .checked(唔係 .selected);陣列 push、join 同 count 係通用補充。
Single select / selected value
var sport = document.forms["f1"].elements["sport"].value;
Lab 9(f):單選 select 可直接取 .value;multiple select 要遍歷 options 或 selectedOptions。
Form processing / display all field values
function print_result() {
  var f = document.forms["f1"];
  var msg = "Name: " + f.elements["name"].value + "\n";
  msg += "Age: " + f.age.value + "\n";
  msg += "URL: " + f.url.value + "\n";
  msg += "Time: " + f.time.value + "\n";
  msg += "Color: " + f.color.value + "\n";
  msg += "Gender: " + f.gender.value + "\n";
  var subjects = [];
  for (var i = 0; i < f.dse.length; i++) {
    if (f.dse[i].checked) subjects.push(f.dse[i].value);
  }
  msg += "DSE: " + subjects.join(", ") + "\n";
  msg += "Sport: " + f.sport.value;
  alert(msg);
}
Lab 9(f):展示八組欄位嘅 value。原教材 onsubmit="print_result()" 唔會阻止提交;若只想顯示結果,改為 onsubmit="return print_result()" 並在函數最後 return false。輸出格式係參考例子。
Custom validation / setCustomValidity()
const field = document.getElementById("code");
field.addEventListener("input", function () {
  field.setCustomValidity("");
  if (field.value === "000000") {
    field.setCustomValidity("This code is not allowed.");
  }
});
補充:需要 id="code" 嘅欄位。非空錯誤訊息令欄位無效;每次驗證前清空舊訊息。
Integer validation / Number.isInteger()
const text = document.getElementById("qty").value;
const n = Number(text);
if (text.trim() !== "" && Number.isInteger(n) && n >= 1) {
  alert("Valid");
}
補充:檢查非空、整數同範圍;Number("") 會變成 0,所以先檢查空字串。

Regular Expression / Regex

HTML pattern 語法速查。Lab 3、9 已有電話、首字母、時間同色碼要求;以下其他格式係通用補充練習,唔係已確認考題。每個例子按實際題目調整長度、字元同 required。

知識點 / Topic內容 / Syntax & Example
HTML pattern / full match / required
Example 1
<input type="text" pattern="[0-9]{6}" required>
Example 2
<input type="text" pattern="[0-9]{6}">
pattern 驗證完整輸入,毋須加 ^ 同 $;唔好加 /.../。冇 required 時空字串可以通過;有 required 就唔可以留空。輸入唔符合時通常係阻止表單提交,唔係阻止輸入。
Regex character classes / 字元種類
[A-Z]      one uppercase letter
[a-z]      one lowercase letter
[A-Za-z]   one English letter
[0-9]      one digit
[A-Za-z0-9] one letter or digit
[^0-9]     one non-digit
.          any character except line terminators
\d         digit (same as [0-9])
\s         whitespace
\S         non-whitespace
\w         letter / digit / underscore (ASCII)
[] 係字元集合,每次匹配一個字元;[^...] 係排除集合。\w 包含底線,唔等於 [A-Za-z0-9]。
Regex quantifiers / 次數與長度
A?       zero or one A
A*       zero or more A
A+       one or more A
A{6}     exactly 6 As
A{2,6}   2 to 6 As
A{2,}    at least 2 As
量詞只作用於前面一個字元、字元集合或者括號群組。{2,6} 中間唔好加空格。
Regex grouping / alternatives / anchors / escape
(AB){2}       ABAB
(A|B)         A or B
^A            starts with A (JS)
Z$            ends with Z (JS)
\.            literal dot
\+            literal plus
\-            literal hyphen
[0-9]{2}      two digits
括號可以組合多個字元;| 表示 OR。HTML pattern 自動要求完整匹配;JavaScript 通常要加 ^ 同 $。現代 HTML pattern 採用 v flag,字元集合內嘅普通連字符要寫 \-,但 A-Z 呢類範圍唔需要。
Exactly 6 characters / fixed length
<input type="text" pattern=".{6}" required>
6 個字元,冇指定一定係英文字母或數字;空格都計。 符合:Ab12!?;不符合:ABC12。
Exactly 6 digits / PIN
<input type="text" pattern="[0-9]{6}" required>
剛好六位數字;用 text 保留開頭嘅 0。 符合:012345;不符合:12345。
Digits only / one or more
<input type="text" pattern="[0-9]+" required>
至少一位數字,唔接受負號同小數點。 符合:123;不符合:12A。
Maximum 8 digits / telephone
<input type="text" pattern="[0-9]{1,8}" required maxlength="8">
最多八位數字。Lab 3 電話要求;如果非必填,可移除 required。 符合:12345678;不符合:123456789。
Exactly 8 digits / Hong Kong phone format
<input type="text" pattern="[0-9]{8}" required>
只驗證八位數字格式,唔代表真實有效電話。 符合:91234567;不符合:1234567。
Phone with optional country code / +852
<input type="text" pattern="(\+852 )?[0-9]{8}" required>
可選 +852 同一個空格;有其他格式要求先修改。 符合:+852 91234567;不符合:852 91234567。
English letters only / alphabetic
<input type="text" pattern="[A-Za-z]+" required>
一個或以上英文字母。 符合:Alice;不符合:Alice1。
Uppercase letters only
<input type="text" pattern="[A-Z]+" required>
只接受大寫英文字母。 符合:ABC;不符合:AbC。
Lowercase letters only
<input type="text" pattern="[a-z]+" required>
只接受小寫英文字母。 符合:abc;不符合:Abc。
Letters or digits / alphanumeric
<input type="text" pattern="[A-Za-z0-9]+" required>
字母或者數字都可以,唔代表兩種類型都必須出現。 符合:AB123;不符合:A_B。
Alphanumeric / exactly 6 characters
<input type="text" pattern="[A-Za-z0-9]{6}" required>
剛好六個英文字母或數字;只有題目指定 alphanumeric 先用。 符合:AB1234;不符合:AB12。
Length range / 4 to 10 letters
<input type="text" pattern="[A-Za-z]{4,10}" required>
4 至 10 個英文字母。 符合:Alice;不符合:ABC。
At least 8 characters / minimum length
<input type="text" pattern=".{8,}" required>
至少八個字元,冇上限。 符合:12345678;不符合:abcdefg。
Capital first character / starts with uppercase
<input type="text" pattern="[A-Z].*" required>
Lab 9(a):只限制第一個字元係大寫英文字母,後面可以係其他字元。 符合:Alice;不符合:alice。
Capitalized word / first uppercase then lowercase
<input type="text" pattern="[A-Z][a-z]*" required>
第一個大寫,其餘零個或以上小寫。若最少要兩個字元,用 [a-z]+。 符合:Alice;不符合:ALICE。
Full name / letters and spaces
<input type="text" pattern="[A-Za-z]+( [A-Za-z]+)*" required>
由一個或以上英文單字組成,用單一空格分隔。呢個係簡化練習,唔涵蓋所有真實姓名。 符合:Alice Chan;不符合: Alice。
Starts with A / ends with Z
<input type="text" pattern="A.*Z" required>
開頭 A、結尾 Z,中間零個或以上字元。 符合:ABZ;不符合:BAZ。
Student ID / prefix and digits
<input type="text" pattern="S[0-9]{7}" required>
例子:大寫 S 加七位數字;唔係指定 VTC 學號格式。 符合:S1234567;不符合:s1234567。
Mixed format / 2 uppercase letters + 4 digits
<input type="text" pattern="[A-Z]{2}[0-9]{4}" required>
先兩個大寫英文字母,再四位數字。 符合:AB1234;不符合:A12345。
Username / letters, digits and underscore
<input type="text" pattern="[A-Za-z0-9_]{4,12}" required>
4 至 12 個字元;可用底線。 符合:user_123;不符合:abc。
Username with literal hyphen / underscore
<input type="text" pattern="[A-Za-z0-9_\-]{4,12}" required>
現代 HTML pattern 嘅字元集合內用 \- 表示普通連字符。 符合:user-123;不符合:abc。
Non-blank text / reject whitespace only
<input type="text" pattern=".*\S.*" required>
至少有一個非空白字元;仍要 required 先會拒絕完全空白。 符合:Hello;不符合: 。
No whitespace / one or more characters
<input type="text" pattern="\S+" required>
唔接受空格、tab 等 whitespace;其他符號仍可出現。 符合:ABC123;不符合:A B。
Time format / HH:MM:SS only
<input type="text" pattern="[0-9]{2}:[0-9]{2}:[0-9]{2}" required>
只限制格式,唔驗證實際時間範圍。Lab 9(d) 可用下方更嚴格版本。 符合:08:30:59;不符合:8:30:59。
Valid 24-hour time / HH:MM:SS
<input type="text" pattern="([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]" required>
小時 00–23,分鐘及秒 00–59。Lab 9(d) 嘅嚴格版本。 符合:23:59:59;不符合:24:00:00。
Date format / YYYY-MM-DD
<input type="text" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" required>
只驗證格式,唔驗證日曆日期。需要有效日期用 type="date"。 符合:2026-12-01;不符合:2026/12/01。
Hex color / 3 or 6 hexadecimal digits
<input type="text" pattern="#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})" required>
Lab 9(e):# 加三位或者六位十六進制字元。 符合:#abc;不符合:#abcd。
Decimal / optional fractional part
<input type="text" pattern="[0-9]+(\.[0-9]+)?" required>
非負數字格式;需要做數值範圍驗證優先用 type="number"。 符合:12;不符合:12.。
Price / exactly two decimal places
<input type="text" pattern="[0-9]+\.[0-9]{2}" required>
貨幣格式:整數部分加小數點,再兩位小數。 符合:12.50;不符合:12.5。
Alternative values / OR / repeated group
<input type="text" pattern="(Yes|No)" required>
接受指定字串其中一個,分大小寫。 符合:Yes;不符合:yes。
Password / at least 8 with letters and digits
<input type="password" pattern="(?=.*[A-Za-z])(?=.*[0-9]).{8,}" required>
補充進階:lookahead 檢查至少一個字母及一個數字。此處容許空格及其他符號;只驗證格式,唔代表密碼安全。 符合:abc12345;不符合:abcdefgh。
Password / uppercase lowercase digit
<input type="password" pattern="(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}" required>
補充進階:至少八個字元,必須有大寫、小寫及數字。 符合:Abc12345;不符合:abc12345。
Email / URL / number / date native validation
Example 1
<input type="email" required>
Example 2
<input type="url" required>
Example 3
<input type="number" min="18" step="1" required>
Example 4
<input type="date" required>
Lab 9(b–c) 用 HTML 原生 input type;Email 係補充。唔需要為基本 email / URL 自行寫複雜 regex;type="email" 唔代表郵箱真實存在。type="number" 唔支援 pattern,應用 min/max/step。
Simple email format / when regex is explicitly requested
<input type="text" pattern="[^\s@]+@[^\s@]+\.[^\s@]+" required>
補充:簡化 email 格式,要求有 @ 同域名句點,但仍可能接受 [email protected] 或 [email protected]。正常優先使用 type="email"。符合:[email protected];不符合:alice@example。
JavaScript RegExp / test() / anchors
var value = "AB1234";
var regex = /^[A-Z]{2}[0-9]{4}$/;
if (regex.test(value)) {
  alert("Valid");
} else {
  alert("Invalid");
}
JavaScript 正則 literal 需要 /.../,用 test() 返回 true 或 false。^、$ 限制一般單行輸入嘅開頭及結尾。HTML pattern 唔需要 /.../。
JavaScript RegExp / constructor / escaping
var re = new RegExp("^\\d{6}$");
re.test("123456"); // true
/^abc$/i.test("ABC"); // true
RegExp constructor 接受字串,反斜線要寫兩次。i flag 代表不分大小寫。HTML pattern 冇呢種 /i 寫法,可用 [A-Za-z]。
HTML validation / checkValidity() / patternMismatch
var input = document.getElementById("code");
if (input.validity.patternMismatch) {
  alert("Invalid format");
}
if (!input.checkValidity()) {
  input.reportValidity();
}
補充 JavaScript:input 要有 id="code";checkValidity() 檢查所有適用限制,包括 required。reportValidity() 顯示瀏覽器提示。Client-side validation 唔可以取代 server-side validation。
Exactly 10 characters / fixed length
<input type="text" pattern=".{10}" required>
補充:剛好十個字元。符合:ABC1234567;不符合:ABC123。
Optional prefix / HK
<input type="text" pattern="(HK)?[0-9]{6}" required>
補充:可選 HK 前綴,跟六位數字。符合:HK123456、123456;不符合:H123456。
Positive integer / no leading zero
<input type="text" pattern="[1-9][0-9]*" required>
補充:大於零嘅整數格式,唔容許前置零。符合:123;不符合:0、012。
Signed integer / optional plus minus
<input type="text" pattern="[\-+]?[0-9]+" required>
補充:正負號可選;HTML pattern 字元集合內連字符要 escape。符合:-123、+123、123;不符合:1.2。
Hong Kong mobile number / simplified format
<input type="tel" pattern="[456789][0-9]{7}" required>
補充:八位數字、首位 4–9 嘅簡化練習規則,唔代表號碼真實或已分配。符合:91234567;不符合:21234567。
Postal code / five digits
<input type="text" pattern="[0-9]{5}" required>
補充:五位數字郵編格式例子,唔係香港郵編規則。符合:01234;不符合:1234。
Letters followed by digits
<input type="text" pattern="[A-Za-z]+[0-9]+" required>
補充:至少一個字母,跟至少一個數字。符合:ABC123;不符合:123ABC。
At least one uppercase letter / lookahead
<input type="text" pattern="(?=.*[A-Z]).+" required>
補充:至少一個大寫字母,其他字元不限。符合:aB1;不符合:abc1。
At least one special character / lookahead
<input type="password" pattern="(?=.*[^A-Za-z0-9\s]).+" required>
補充:至少一個非 ASCII 英文字母、數字或空白嘅字元;亦會接受非 ASCII 字母。符合:abc!;不符合:abc123。
Email / domain labels and dot (simplified stricter)
<input type="email" pattern="[^\s@]+@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z0-9]+(-[A-Za-z0-9]+)*)*\.[A-Za-z]{2,}" required>
補充:原生 email 驗證加簡化域名格式,拒絕空 domain label。符合:[email protected];不符合:[email protected]、[email protected]。並非完整 email 標準,唔驗證郵箱存在。