Froms API
写在前面:
兼容性:多层 自动降级
有时候我会用库
新的表单特性和函数:浏览器不支持的时候会直接忽略。
1、新表单特性和函数
placeholder:向用户显示描述性说明或提示信息,如:。
autocomplete:用来保护敏感用户数据,避免本地浏览器进行存储 ,主要有 on(字段值无需保护)、off(字段值需要保护)、unspecified三种行为。如:
autofocus:指定某个表单元素获得输入焦点
list和datalist:组合使用这两个特性可以为输入型控件构造一张选值列表,使用方法如下:
(1)创建id值唯一的datalist元素,可以在文档任意位置插入;
(2)添加若干option元素,如:
<datalist id="contactList">
<option value="2@xx.com" label="Racer">
<option value="3@xx.com" label="Perter">
</datalist>
(3)将input的list特性值设置为datalist的id值
min和max:主要用于range元素
step:指定输入值递增或递减的粒度。
valueAsNumber函数:完成控件值类型在文本与数值间的相互转换
required:指定表单元素为必填
2、表单验证
valueMissing
目的:确保表单控件中的值已填写
用法:设置控件的required为true
typeMismatch
目的:保证控件值与预期类型相匹配
用法:指定 表单控件的type特性值
patterMismatch
目的:根据控件设置的格式规则验证输入是否为有效格式
用法:指定控件的pattern特性,并赋予适当的匹配规则
tooLong
目的:避免值包含过多字符
用法:设定控件的maxLength特性
rangeUnderFlow
目的:限制数值型控件的最小值
用法:设置控件的min特性,并赋值
rangeOverflow
目的:限制数值型控件的最大值
用法:设置控件的max特性,并赋值
stepMismatch
目的:确保输入值符合min、max及step设置
用法:设置控件的step特性,并赋值
customError
目的:处理代码及计算产生的错误
用法:调用setCustomValidity((message)将控件置于customError状态
注意:还可以通过表单控件来访问ValidityState对象,如var check = documenet.myForm.myInput.validity;然后调用check.valid。
3、验证反馈
在HTML5中,如果开发人员想把错误消息反馈给用户,可以使用invalid事件。
function invalidHandler(evt){
var validity = evt.srcElement.valididy;
if(validity.valueMissing){
//提示用户必填项中没有填值
}
//检测其他约束条件
//如果不希望浏览器提供默认的验证反馈,可以取消事件
evt.preventDefault();
}
//注册 invalid事件的监听器__halt_compiler
myField.addEventListener("invalid",invalidHandler,false)
还可以通过设置noValidate特性来关闭验证。
formnovalidate - 重写表单的 novalidate 属性
4、代码Demo
完整案例:
4.1-注册页面:
<!DOCTYPE html>
<html>
<head>
<title>Tahoe 216</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<link rel="stylesheet" href = "html5.css">
<style type="text/css">
label {
text-align: right;
width: 90px;
float: left;
}
input {
margin-top: 0px;
padding-top: 0px;
}
fieldset {
margin-top: 5px;
}
#confidenceDisplay {
vertical-align: top;
}
</style>
<script>
function setConfidence(newVal) {
document.getElementById("confidenceDisplay").innerHTML = newVal + '%';
}
function invalidHandler(evt) {
// find the label for this form control
var label = evt.srcElement.parentElement.getElementsByTagName("label")[0];
// set the label's text color to red
label.style.color = 'red';
// stop the event from propagating higher
evt.stopPropagation();
// stop the browser's default handling of the validation error
evt.preventDefault();
}
function loadDemo() {
// register an event handler on the form to
// handle all invalid control notifications
document.register.addEventListener("invalid", invalidHandler, true);
}
window.addEventListener("load", loadDemo, false);
</script>
</head>
<body>
<div id="container">
<header>
<h1>Tahoe 216</h1>
<h3 align="center">3 Days, 216-Miles, One Crazy Runner's High</h3>
<h2> </h2>
<h4>Live Results Now!</h4>
</header>
<nav>
<h2>Links</h2>
<a href="index.html" title="Home">Home</a>
<a href="signup.html" title="Are you crazy enough?">Sign Up</a>
<a href="about.html" title="Learn more about the T216">About the Race</a>
</nav>
<section>
<article>
<h2>Sign Up Today</h2>
<p><strong>Race fee</strong>: $216 </p>
<p>Make check payable to the Happy Trails Running Club</p>
<p><strong>Note</strong>: We recommend that you seek your doctor's and family's approval before you sign up. Race fees are not refundable. </p>
<form name="register">
<p><label for="runnername">Runner:</label>
<input id="runnername"name="runnername" type="text"
placeholder="First and last name" required></p>
<p><label for="phone">Tel #:</label>
<input id="phone" name="phone" type="tel"
placeholder="(xxx) xxx-xxx"></p>
<p><label for="emailaddress">E-mail:</label>
<input id="emailaddress" name="emailaddress" type="email"
placeholder="For confirmation only"></p>
<p><label for="dob">DOB:</label>
<input id="dob" name="dob" type="date"
placeholder="MM/DD/YYYY"></p>
<fieldset>
<legend>T-shirt Size: </legend>
<p><input id="small" type="radio" name="tshirt" value="small">
<label for="small">Small</label></p>
<p><input id="medium" type="radio" name="tshirt" value="medium">
<label for="medium">Medium</label></p>
<p><input id="large" type="radio" name="tshirt" value="large">
<label for="large">Large</label></p>
<p><label for="style">Shirt style:</label>
<input id="style" name="style" type="text" list="stylelist" title="Years of participation"></p>
<datalist id="stylelist">
<option value="White" label="1st Year">
<option value="Gray" label="2nd - 4th Year">
<option value="Navy" label="Veteran (5+ Years)">
</datalist>
</fieldset>
<fieldset>
<legend>Expectations:</legend>
<p>
<label for="confidence">Confidence:</label>
<input id="confidence" name="level" type="range"
onchange="setConfidence(this.value)"
min="0" max="100" step="5" value="0">
<span id="confidenceDisplay">0%</span></p>
<p><label for="notes">Notes:</label>
<textarea id="notes" name="notes" maxLength="140"></textarea></p>
</fieldset>
<p><input type="submit" name="register" value="Register"></p>
</form>
</article>
</section>
<aside>
<h2>Sponsors</h2>
<p align="center">Happy Trails Running Club</p>
<p align="center"><img src="happy-trails-rc.gif" alt="Happy Trails Running Club" width="149" height="207"></p>
</aside>
<footer>
<p>Powered by HTML5</p>
</footer>
</div>
</body>
</html>
4.2-密码是否一致重写验证:
<!DOCTYPE html>
<html>
<head>
<title>Password Match</title>
<script>
function checkPasswords() {
var pass1 = document.getElementById("password1");
var pass2 = document.getElementById("password2");
if (pass1.value != pass2.value)
pass1.setCustomValidity("Your passwords do not match. Please recheck that your new "+"password is entered identically in the two fields.");
else
pass1.setCustomValidity("");
}
function invalidHandler(evt) {
// set the label's text color to red
evt.srcElement.style.background = 'red';
// stop the event from propagating higher
evt.stopPropagation();
// stop the browser's default handling of the validation error
evt.preventDefault();
}
function loadDemo() {
// register an event handler on the form to
// handle all invalid control notifications
document.passwordChange.addEventListener("invalid", invalidHandler, true);
}
window.addEventListener("load", loadDemo, false);
</script>
</head>
<body>
<form name="passwordChange">
<p><label for="password1">New Password:</label>
<input type="password" id="password1" onchange="checkPasswords()"></p>
<p><label for="password2">Confirm Password:</label>
<input type="password" id="password2" onchange="checkPasswords()"></p>
</form>
<button onclick="document.passwordChange.password1.checkValidity()">Check Validity</button>
</body>
</html>
在Chrome显示效果:
在FireFox显示效果:
4.3-输入过滤:
<!DOCTYPE html>
<html>
<head>
<title>Pattern List</title>
<!--
This demo does not yet work in any browsers at the time of publication.
It was planned to be an additional Practical Extra called "Natural (List) Selection".
It was meant to show how you can use patterns to restrict the values in a datalist
live so that as the user types, the datalist options are filtered. Datalists are only
supported in Opera at the moment, and this demo works there. Sort of. Unfortunately,
when the pattern is applied, the visuals of the list don't actually reflect that
until the next keypress. So it always lags behind by one key. I tried everything I
could to force it to refresh the list immediately, but to no avail. Maybe this will
work when other browsers like Chrome and Safari add their datalist support.
-->
<script>
function filterList(field) {
// get the current value from the field
var currVal = field.value;
// escape any regular expression characters from the entered text
currVal = currVal.replace(/([.*+?|(){}[\]\\])/ig, "\\$1");
field.pattern = currVal + ".*";
}
</script>
</head>
<body>
<form name="listForm">
<p><label for="patternList">Select from the list:</label>
<input type="text" id="patternChoice" list="fullList" onkeydown="filterList(this)"></p><!-- this 表示是输入框-->
<datalist id="fullList">
<option value="one">
<option value="two">
<option value="three">
<option value="four">
<option value="five">
<option value="six">
<option value="seven">
<option value="eight">
<option value="nine">
<option value="ten">
</datalist>
<span>Type in the field to filter the options.</span>
</form>
</body>
</html>