该示例检查从文本窗口部件中获取姓名和电话号码这两个表单数据的有效性。当文本框中的值发生变化时,即引发一个change事件,从而可以调用一个函数来检查这两个输入值的格式是否正确。
validator.html源代码如下
<!DOCTYPE html>
<html>
<head>
<title>validator.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="validator.js"></script>
</head>
<body>
<h3>Customer Infomation</h3>
<form action="">
<p>
<label>
<input type="text" id="custName"/>name(last name,first name,middle initial)
</label>
<br/><br/>
<label>
<input type="text" id="phone"/>phone number(ddd-ddd-dddd)
</label>
<br/><br/>
<input type="reset" id="reset"/>
<input type="submit" id="submit"/>
</p>
</form>
<script type="text/javascript" src="validatorr.js"></script>
</body>
</html>
validator.js源代码如下:
function chkName(){
var myName=document.getElementById("custName");
var pos=myName.value.search(/^[A-Z][a-z]+,?[A-Z][a-z]+,?[A-Z]\.?$/);
if(pos!=0){
alert("The name you entered ("+myName.value+") is not in the correct form. \n"+
"The correct form is:"+"last-name,first-name,middle-initial \n"+
"Please go back and fix your name");
return false;
}else{
return true;
}
}
function chkPhone(){
var myPhone=document.getElementById("phone");
var pos=myPhone.value.serch(/^\d{3}-\d{3}-\d{4}$/);
if(pos!=0){
alert("The phone number you entered ("+myPhone.value+") is not in the correct form. \n"+
"The correct form is:ddd-ddd-dddd \n"+
"Please go back and fix your phone number");
return false;
}else{
return true;
}
}
validatorr.js源代码如下:
document.getElementById("custName").onchange=chkName;
document.getElementById("phone").onchange=chkPhone;
程序界面如下: