JavaScript 表單驗(yàn)證
JavaScript 表單驗(yàn)證
avaScript 可用來(lái)在數(shù)據(jù)被送往服務(wù)器前對(duì) HTML 表單中的這些輸入數(shù)據(jù)進(jìn)行驗(yàn)證。
表單數(shù)據(jù)經(jīng)常需要使用 JavaScript 來(lái)驗(yàn)證其正確性:
- 驗(yàn)證表單數(shù)據(jù)是否為空鸵闪?
- 驗(yàn)證輸入是否是一個(gè)正確的email地址靶擦?
- 驗(yàn)證日期是否輸入正確坷襟?
- 驗(yàn)證表單輸入內(nèi)容是否為數(shù)字型构蹬?
必填(或必選)項(xiàng)目
下面的函數(shù)用來(lái)檢查用戶是否已填寫(xiě)表單中的必填(或必選)項(xiàng)目溃蔫。假如必填或必選項(xiàng)為空皆疹,那么警告框會(huì)彈出,并且函數(shù)的返回值為 false膀曾,否則函數(shù)的返回值則為 true(意味著數(shù)據(jù)沒(méi)有問(wèn)題)
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("姓必須填寫(xiě)");
return false;
}
}
以上函數(shù)在 form 表單提交時(shí)被調(diào)用
<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
姓: <input type="text" name="fname">
<input type="submit" value="提交">
</form>
E-mail 驗(yàn)證
輸入的數(shù)據(jù)必須包含 @ 符號(hào)和點(diǎn)號(hào)(.)县爬。同時(shí),@ 不可以是郵件地址的首字符添谊,并且 @ 之后需有至少一個(gè)點(diǎn)號(hào)
function validateForm(){
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
alert("不是一個(gè)有效的 e-mail 地址");
return false;
}
}
下面是連同 HTML 表單的完整代碼
<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="提交">
</form>
JavaScript 驗(yàn)證 API
約束驗(yàn)證 DOM 方法
checkValidity()
如果 input 元素中的數(shù)據(jù)是合法的返回 true,否則返回 false察迟。
setCustomValidity()
設(shè)置 input 元素的 validationMessage 屬性斩狱,用于自定義錯(cuò)誤提示信息的方法。
使用 setCustomValidity 設(shè)置了自定義提示后扎瓶,validity.customError 就會(huì)變成true所踊,則 checkValidity 總是會(huì)返回false。如果要重新判斷需要取消自定義提示概荷,方式如下:
setCustomValidity('')
setCustomValidity(null)
setCustomValidity(undefined)
以下實(shí)例如果輸入信息不合法秕岛,則返回錯(cuò)誤信息
checkValidity() 方法
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">驗(yàn)證</button>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
約束驗(yàn)證 DOM 屬性
validity 布爾屬性值,返回 input 輸入值是否合法
validationMessage 瀏覽器錯(cuò)誤提示信息
willValidate 指定 input 是否需要驗(yàn)證
Validity 屬性
input 元素的 validity 屬性包含一系列關(guān)于 validity 數(shù)據(jù)屬性
customError 設(shè)置為 true, 如果設(shè)置了自定義的 validity 信息。
patternMismatch 設(shè)置為 true, 如果元素的值不匹配它的模式屬性继薛。
rangeOverflow 設(shè)置為 true, 如果元素的值大于設(shè)置的最大值修壕。
rangeUnderflow 設(shè)置為 true, 如果元素的值小于它的最小值。
stepMismatch 設(shè)置為 true, 如果元素的值不是按照規(guī)定的 step 屬性設(shè)置遏考。
tooLong 設(shè)置為 true, 如果元素的值超過(guò)了 maxLength 屬性設(shè)置的長(zhǎng)度慈鸠。
typeMismatch 設(shè)置為 true, 如果元素的值不是預(yù)期相匹配的類(lèi)型。
valueMissing 設(shè)置為 true灌具,如果元素 (required 屬性) 沒(méi)有值青团。
valid 設(shè)置為 true,如果元素的值是合法的咖楣。
如果輸入的值大于 100督笆,顯示一個(gè)信息
如果輸入的值小于 100,顯示一個(gè)信息
<input id="id1" type="number" min="100" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
var inpObj = document.getElementById("id1");
if(!isNumeric(inpObj.value)) {
txt = "你輸入的不是數(shù)字";
} else if (inpObj.validity.rangeUnderflow) {
txt = "輸入的值太小了";
} else {
txt = "輸入正確";
} document.getElementById("demo").innerHTML = txt;
}
// 判斷輸入是否為數(shù)字
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>
JavaScript 保留關(guān)鍵字
一些標(biāo)識(shí)符是保留關(guān)鍵字诱贿,不能用作變量名或函數(shù)名
JavaScript 標(biāo)準(zhǔn)
ECMAScript 5(ES5胖腾,2009 年發(fā)布),是 JavaScript 最新的官方版本
JavaScript 保留關(guān)鍵字
Javascript 的保留關(guān)鍵字不可以用作變量瘪松、標(biāo)簽或者函數(shù)名咸作。有些保留關(guān)鍵字是作為 Javascript 以后擴(kuò)展使用
abstract arguments boolean break byte
case catch char class* const
continue debugger default delete do
double else enum* eval export*
extends* false final finally float
for function goto if implements
import* in instanceof int interface
let long native new null
package private protected public return
short static super* switch synchronized
this throw throws transient true
try typeof var void volatile
while with yield
* 標(biāo)記的關(guān)鍵字是 ECMAScript5 中新添加的。
JavaScript 對(duì)象宵睦、屬性和方法
避免使用 JavaScript 內(nèi)置的對(duì)象记罚、屬性和方法的名稱作為 Javascript 的變量或函數(shù)名
Array Date eval function hasOwnProperty
Infinity isFinite isNaN isPrototypeOf length
Math NaN name Number Object
prototype String toString undefined valueOf
Java 保留關(guān)鍵字
避免使用一些 Java 對(duì)象和屬性作為 JavaScript 標(biāo)識(shí)符
getClass java JavaArray
javaClass JavaObject JavaPackage
Windows 保留關(guān)鍵字
在 HTML 中,必須(為了可移植性壳嚎,您也應(yīng)該這么做)避免使用 HTML 和 Windows 對(duì)象和屬性的名稱作為 Javascript 的變量及函數(shù)名
alert all anchor anchors area
assign blur button checkbox clearInterval
clearTimeout clientInformation close closed confirm
constructor crypto decodeURI decodeURIComponent defaultStatus
document element elements embed embeds
encodeURI encodeURIComponent escape even fileUpload
focus form forms frame innerHeight
innerWidth layer layers link location
mimeTypes navigate navigator frames frameRate
hidden history image images offscreenBuffering
open opener option outerHeight outerWidth
packages pageXOffset pageYOffset parent parseFloat
parseInt password pkcs11 plugin prompt
propertyIsEnum radio reset screenX screenY
scroll secure select self setInterval
setTimeout status submit taint text
textarea top unescape untaint window
HTML 事件句柄
避免使用 HTML 事件句柄的名稱作為 Javascript 的變量及函數(shù)名
onblur onclick onerror onfocus
onkeydown onkeypress onkeyup onmouseover
onload onmouseup onmousedown onsubmit
非標(biāo)準(zhǔn) JavaScript
const 關(guān)鍵字桐智,用于定義變量。 一些 JavaScript 引擎把 const 當(dāng)作 var 的同義詞烟馅。另一些引擎則把 const 當(dāng)作只讀變量的定義说庭。
Const 是 JavaScript 的擴(kuò)展。JavaScript 引擎支持它用在 Firefox 和 Chrome 中郑趁。但是它并不是 JavaScript 標(biāo)準(zhǔn) ES3 或 ES5 的組成部分刊驴。建議:不要使用它。