# Form Widgets
# Drop-down content
# optgroup
<select id="groups" name="groups">
<optgroup label="fruits">
<option>Banana</option>
<option selected>Cherry</option>
<option>Lemon</option>
</optgroup>
<optgroup label="vegetables">
<option>Carrot</option>
<option>Eggplant</option>
<option>Potato</option>
</optgroup>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Behold: Demo
# Autocomplete box
<label for="myFruit">What's your favorite fruit?</label>
<input type="text" name="myFruit" id="myFruit" list="mySuggestion" />
<datalist id="mySuggestion">
<option>Apple</option>
<option>Banana</option>
<option>Blackberry</option>
<option>Blueberry</option>
<option>Lemon</option>
<option>Lychee</option>
<option>Peach</option>
<option>Pear</option>
</datalist>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Behold: Demo
# Advanced Widgets
# Numbers
<input type="number" name="age" id="age" min="1" max="10" step="2" />
1
# Sliders
<input type="range" name="beans" id="beans" min="0" max="500" step="10" />
1
Behold: Demo
# Validation Of Forms
以前写表单验证总是在 js 里写正则表达式, 但是今天看了 MDN 的文档才发现原来将正则表达式写在 HTML 里才是更方便的方法, 只要在 input
里添加 pattern
属性, 其值就是正则表达式, Behold:
<form>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input id="choose" name="i_like" required pattern="banana|cherry" />
<button>Submit</button>
</form>
1
2
3
4
5
2
3
4
5
上面代码中, 输入框里只接受 banana 和 cherry 两个选项.
当然, 使用 js+css customize 更完善一些.
# 限制输入框的字符长度
<form>
<div>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input
type="text"
id="choose"
name="i_like"
required
minlength="6"
maxlength="6"
/>
</div>
<div>
<label for="number">How many would you like?</label>
<input type="number" id="number" name="amount" value="1" min="1" max="10" />
</div>
<div>
<button>Submit</button>
</div>
</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 自定义错误信息
我们不会满足于 HTML 内置的验证报错提示的样式, 因为它在某种程度上可以说是很难看, 当然我们有空间去这样做.
为了实现自定义的 validation, 我们需要使用到 JavaScript 的 API 来辅助完成.Behold:
<form>
<label for="mail">I would like you to provide me an e-mail</label>
<input type="email" id="mail" name="mail" />
<button>Submit</button>
</form>
1
2
3
4
5
2
3
4
5
在 JS 里, 我们可以使用 setCustomValidity()
方法:
var email = document.getElementById("mail");
email.addEventListener("input", function(e) {
email.validity.typeMismatch
? email.setCustomValidity("我要e-mail! 亲!")
: email.setCustomValidity("");
});
1
2
3
4
5
6
2
3
4
5
6
当然, constraint validation API 实在是太多了, 这里不可能一个个介绍, 更详细的还是在mdn里面