一、用法簡介:
表單驗證函數(shù)放在了functions.js文件里了,在你所需要做驗證的網(wǎng)頁文件里,包含該腳本文件。一般語法為:
<script type="text/javascript" src="./functions.js">
對于焦點失去驗證,為表單控件的onBlur事件綁定相應(yīng)的驗證函數(shù),用法如下:
整型?? checkNumber()
浮點型 checkNumber()
字符串 checkString()
日期?? checkDate()
郵箱?? checkEmail()
示例 onBlur="checkNumber()"
對于表單提交驗證,在表單提交前進行判斷,用法如下:
if(checkForm('表單名稱'))
{
? 表單名稱.submit();
? return true;
}
else
{
? return false;
}
也可以綁定表單onSubmit事件,用法如下:
onSubmit="return checkForm('表單名稱')"
二、類型定義:
1、整型(int)
定義:
? valueType="int"
屬性:
? objName?? 對象名稱(字符串)
? mustInput 必輸項(true/false)
? minInput? 最小值(數(shù)字)
? maxInput? 最大值(數(shù)字)
舉例:
? <input type="text" name="test" valueType="int" objName="總載重噸" mustInput="true" maxInput="10000">
2、浮點型(float)
定義:
? valueType="float"
屬性:
? objName?? 對象名稱(字符串)
? mustInput 必輸項(true/false)
? minInput? 最小值(數(shù)字)
? maxInput? 最大值(數(shù)字)
? decimalLen小數(shù)位數(shù)(數(shù)字)
舉例:
? <input type="text" name="test" valueType="float" objName="運價" mustInput="true" maxInput="10000.50" decimalLen="2">
3、字符串(string)
定義:
? valueType="string"
屬性:
? objName?? 對象名稱(字符串)
? mustInput 必輸項(true/false)
? stringLen 字符串長度(數(shù)字)
舉例:
? <input type="text" name="test" valueType="string" objName="英文船名" mustInput="true" stringLen="100">
4、日期(date)
定義:
? valueType="date"
屬性:
? objName?? 對象名稱(字符串)
? mustInput 必輸項(true/false)
舉例:
? <input type="text" name="test" valueType="date" objName="開始日期" mustInput="true">
備注:
? 日期現(xiàn)在只能校驗的格式為(yyyy-mm-dd)
5、郵箱(email)
定義:
? valueType="email"
屬性:
? objName?? 對象名稱(字符串)
? mustInput 必輸項(true/false)
舉例:
? <input type="text" name="test" valueType="email" objName="郵箱" mustInput="true">
6、單選(radio)? 暫沒調(diào)試成功
定義:
? valueType="radio"
屬性:
? objName?? 對象名稱(字符串)
? mustSelect 必輸項(true/false)
舉例:
? <input type="radio" name="test" valueType="radio" objName="租船方式" mustSelect="true">
備注:
? 對于同一組單選按鈕,只需要定義第一個即可。
7、復(fù)選(checkbox) 暫沒調(diào)試成功
定義:
? valueType="checkbox"
屬性:
? objName?? 對象名稱(字符串)
? minSelect 最小選擇數(shù)(數(shù)字)
? maxSelect 最大選擇數(shù)(數(shù)字)
舉例:
? <input type="checkbox" name="test" valueType="checkbox" objName="愛好" minSelect="2" maxSelect="5">
備注:
? 對于同一組復(fù)選按鈕,只需要定義第一個即可。
8、下拉列表框(select)
定義:
? valueType="select"
屬性:
? objName?? 對象名稱(字符串)
? mustSelect 必輸項(true/false)
舉例1:
? <select name="test" valueType="select" objName="租船方式" mustSelect="true">
舉例2:
<select name="test" valueType="select" objName="租船方式" mustSelect="true">
?<option type="checkbox" name="test2" >請選擇<option>
?<option type="checkbox" name="test2" >3 <option>
?<option type="checkbox" name="test2" >4 <option>
</select>
9、列表框(list)
定義:
? valueType="list"
屬性:
? objName?? 對象名稱(字符串)
? minSelect 最小選擇數(shù)(數(shù)字)
? maxSelect 最大選擇數(shù)(數(shù)字)
舉例:
? <select name="test" valueType="list" objName="愛好" size =5 minSelect="2" maxSelect="5">
三、程序文件
/*****************functions.js**********************/
/***檢查表單所有元素***/
function checkForm(formName)
{
??? var oForm=document.all(formName);
? var eles = oForm.elements;
? //var els
?
??? //遍歷所有表元素
? for(var i=0;i<eles.length;i++)
??? {
??????? //是否需要驗證
??????? var sType=eles[i].valueType;
?????
? if(sType)
??????? {
????????
??? if(eles[i].mustInput!=null && eles[i].mustInput=="true"
??? {
???? //els=eles[i].value;
???? //els=trim(els);
??? if(trim(eles[i].value)==""
??? {
???? if(eles[i].objName!=null)
???? {
?????? alert(eles[i].objName+" 不可以為空";
???? }
???? else
???? {
?????? alert("該文本框為必輸字段";
???? }
???? eles[i].focus();?????
???? event.returnValue=false;?????
???? return false;???
??? }
? }
? switch(sType)
?? {
??? //整數(shù)
??? case "int":
???? if(!validInt(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //小數(shù)
??? case "float":
???? if(!validFloat(eles[i]))
???? {?
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //字符串
??? case "string":
???? if(!validString(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //日期
??? case "date":
???? if(!validDate(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //郵件
??? case "email":
???? if(!validEmail(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //單選按鈕
??? /*case "radio":
???? if(!validRadio(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //復(fù)選按鈕
??? case "checkbox":
???? if(!validBox(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;*/
??? //下拉列表框
??? case "select":
???? if(!validSelect(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
??? //列表框
??? case "list":
???? if(!validList(eles[i]))
???? {
????? event.returnValue=false;
????? return false;
???? }
???? break;
}?
? }
???? }
???? event.returnValue=true;
?return true;
}?
/***驗證是否為整數(shù)***/
function validInt(ele)
{
?if(!isInt(ele.value))
?{
? alert("請輸入有效整數(shù)";
? ele.focus();
? return false;
?}
?else
?{
? if(ele.maxInput!=null && !isNaN(ele.maxInput))
?? if(parseInt(ele.maxInput)<parseInt(ele.value))
?? {
???? alert("您輸入的 "+ convertNullToSpace(ele.objName)+" 值應(yīng)該小于"+ele.maxInput);?????????
??? ele.focus();
??? return false;
?? }??????
? if(ele.minInput!=null && !isNaN(ele.minInput))
?? if(parseInt(ele.minInput)>parseInt(ele.value))
?? {
??? alert("您輸入的 "+ convertNullToSpace(ele.objName)+" 值應(yīng)該大于"+ele.minInput);
??? ele.focus();
??? return false;
?? }???
?}
?return true;
}
/***判斷是否為整數(shù)***/
function isInt(s)
{
?var patrn=/^0|^[1-9]\d*/;
?if (!patrn.exec(s))
?{
??? return false;
?}
?else
?{
? return true;
?}
}
/***驗證是否為小數(shù)***/
function validFloat(ele)
{
??? if(isNaN(ele.value))
??? {
? alert("請輸入有效數(shù)字";
? ele.focus();
? return false;
??? }
?else
?{
????? if(ele.decimalLen!=null && !checkDecimal(ele.value,ele.decimalLen))
???? {
?? alert("您輸入的 "+convertNullToSpace(ele.objName)+" 值小數(shù)位最多為"+ele.decimalLen+"個小數(shù)位";
?? ele.focus();?????
?? return false;
????? }?
? if(ele.maxInput!=null && !isNaN(ele.maxInput))
?? if(parseInt(ele.maxInput)<parseInt(ele.value))
?? {
???? alert("您輸入的 "+ convertNullToSpace(ele.objName)+" 值應(yīng)該小于"+ele.maxInput);???????????
??? ele.focus();
??? return false;
?? }??????
? if(ele.minInput!=null && !isNaN(ele.minInput))
?? if(parseInt(ele.minInput)>parseInt(ele.value))
?? {
??? alert("您輸入的 "+ convertNullToSpace(ele.objName)+" 值應(yīng)該大于"+ele.minInput);
??? ele.focus();
??? return false;
?? }???
?}
?return true;
}
/***驗證是否為字符串***/
function validString(ele)
{
?if(ele.stringLen!=null && !isNaN(ele.stringLen))
?{
? var value=new String(ele.value);
? if(value.length>parseInt(ele.stringLen))
? {
?? alert("您輸入的 "+convertNullToSpace(ele.objName)+" 字數(shù)最大長度為"+ele.stringLen);
?? ele.focus();?????
?? return false;
? }
?}
?return true;
}
/***驗證是否為日期格式***/
function validDate(ele)
{
?if(!isDate(ele.value)&&ele.value!=""
?{
? alert("請輸入有效日期(yyyy-mm-dd)";
? ele.focus();
? return false;
??? }
?return true;
}
/***判斷是否為日期***/
function isDate(str)
{
?var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})/);?
?if(r==null)
?{
? return false;
?}?
?var d= new Date(r[1], r[3]-1, r[4]);?
?if(!(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]))
?{??
? return false;
?}
?return true;
}
/***驗證是否為電子郵箱***/
function validEmail(ele)
{
?if(!isEmail(ele.value))
?{
? alert("請輸入有效郵箱";
? ele.focus();
? return false;
??? }
?return true;
}
/***判斷是否為郵箱***/
function isEmail(str)
{
?if(str.match(/[\w-.]+@{1}[\w-]+\.{1}\w{2,4}(\.{0,1}\w{2}){0,1}/ig)!=str)
? return false;
?else
? return true;
}
/***驗證單選按鈕是否需要選擇***/
function validRadio(ele)
{
?//var rads = document.getElementsByName(ele.name);
?
??? eval("var rads="+name+"."+ele.name);
?var selectCount=0;
?for(var i=0;i<rads.length;i++)
??? {
? if(rads[i].checked)
??????? {
?? selectCount++;
??????? }
??? }
?
?if(ele.mustSelect!=null && ele.mustSelect)
?{
? if(selectCount==0)
? {
?? alert("請選擇"+convertNullToSpace(ele.objName));
?? ele.focus();?????
?? return false;
? }
?}
?return true;
}
/***驗證復(fù)選按鈕是否需要選擇***/
function validBox(ele)
{
?//var rads = document.getElementsByName(ele.name);
??? eval("var chks="+name+"."+ele.name);
?var selectCount=0;
?for(var i=0;i<chks.length;i++)
??? {
? if(chks[i].checked)
??????? {
?? selectCount++;
??????? }
??? }
?if(ele.minSelect!=null && !isNaN(ele.minSelect))
?{
? if(selectCount<parseInt(ele.minSelect))
? {
?? alert(convertNullToSpace(ele.objName)+"至少選擇"+ele.minSelect+"項";
?? ele.focus();?????
?? return false;
? }
?}
?if(ele.maxSelect!=null && !isNaN(ele.maxSelect))
?{
? if(selectCount>parseInt(ele.maxSelect))
? {
?? alert(convertNullToSpace(ele.objName)+"至多選擇"+ele.maxSelect+"項";
?? ele.focus();?????
?? return false;
? }
?}
?return true;
}
/***驗證下拉列表框是否需要選擇***/
function validSelect(ele)
{
?//var rads = document.getElementsByName(ele.name);
?if(ele.mustSelect!=null && ele.mustSelect)
?{
? if(ele.selectedIndex==0)
? {
?? alert("請選擇"+convertNullToSpace(ele.objName));
?? ele.focus();?????
?? return false;
? }
?}
?return true;
}
/***驗證列表框的選擇項數(shù)***/
function validList(ele)
{
?//var rads = document.getElementsByName(ele.name);
??? var selectCount=0;
?for(var i=0;i<ele.options.length;i++)
??? {
??????? if(ele.options[i].selected)
??????? {
??????????? selectCount++;
??????? }
??? }
?
?if(ele.minSelect!=null && !isNaN(ele.minSelect))
?{
? if(selectCount<parseInt(ele.minSelect))
? {
?? alert(convertNullToSpace(ele.objName)+"至少選擇"+ele.minSelect+"項";
?? ele.focus();?????
?? return false;
? }
?}
?if(ele.maxSelect!=null && !isNaN(ele.maxSelect))
?{
? if(selectCount>parseInt(ele.maxSelect))
? {
?? alert(convertNullToSpace(ele.objName)+"至多選擇"+ele.maxSelect+"項";
?? ele.focus();?????
?? return false;
? }
?}
?return true;
}
/***將NULL轉(zhuǎn)化為空格,用于顯示對象名稱***/
function convertNullToSpace(paramValue)
{
? if(paramValue==null)
??? return "";
? else?
??? return paramValue;
}
/***檢查小數(shù)位數(shù)***/
function checkDecimal(num,decimalLen)
{
? var len = decimalLen*1+1;
? if(num.indexOf('.')>0)
? {
??? num=num.substr(num.indexOf('.')+1,num.length-1);??
??? if ((num.length)<len)
?{
????? return true;
??? }
?else
?{
????? return false;
??? }
? }
? return true;
}
/***去除空格***/?
function trim(str)?
?{?
? if (str.length > 0)?
? {
?? while ((str.substring(0,1) == " ") && (str.length > 0))
?? {
??? str = str.substring(1,str.length);
?? }
?? while (str.substring(str.length-1,str.length) == " ")
?? { str = str.substring(0,str.length-1); }
? }
? return str;
?}
===============================================================
函數(shù)Reset()按Reset按鈕后對各字段的內(nèi)容復(fù)位。
函數(shù)submitForms()按submit按鈕后對字段合法性檢查后發(fā)送電子郵件。
函數(shù)isName()對姓名字段進行合法性檢查。
函數(shù)isEmail()對電子郵件地址字段進行合法性檢查。
函數(shù)isBrowser()對瀏覽器字段與自動檢測的瀏覽器版本進行比較。
函數(shù)isCountry()對國家字段進行合法性檢查。
函數(shù)isComment()對意見字段進行合法性檢查,不允許為空值。
函數(shù)isFavorite()對喜歡的站點字段進行合法性檢查,不允許為空值。
程序中還提供了一些技巧,例如,如何判斷瀏覽器的版本,字符串的操作等等。
結(jié)果是以電子郵件的形式提供給你的,里面有客人輸入的各個字段。程序比較長,但不難看懂,下面是源代碼:
<HTML>
<HEAD>
<TITLE> 用JavaScript 編 制 留 言 簿 程 序</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
//Someone@abc.com 是 你 自 己 的 電 子 郵 件 地 址
var emailAddress="Someone@abc.com";
function toName()
????? {
var toNameval=document.forms[0].elements[1].value;
toNameval = "mailto:Someone@abc.com?subject=Guest Book example";
this.document.mail.action = toNameval;
}
function Reset() {
document.forms[0].elements[0].value = "";
document.forms[0].elements[1].value = "";
document.forms[0].elements[2].value =
navigator.appName + " " + navigator.appVersion;??
document.forms[0].elements[3].value = "";
document.forms[0].elements[4].value = "";
document.forms[0].elements[5].value = "";
document.forms[0].elements[0].focus();
}
function submitForms() {
if ( (isName() ) && (isEmail()) && (isBrowser())
&& (isCountry()) && (isComment()) && (isFavorite()) )
if (confirm("\nYou're about to e-mail the form.\n\nClick
on YES to submit.\n\nClick on NO to abort."))
{
alert("\nYour submission will now be made to :
\n\n"+emailAddress+"\n\n\nThank you!");
return true;
}
else
{
alert("\nYou have chosen to abort the submission.");
return false;??????
}
else
return false;
}
function isName() {
var str = document.forms[0].elements[0].value;
if (str == "") {
alert("\nThe NAME field is blank.\n\nPlease enter your name.")
document.forms[0].elements[0].focus();
return false;
}
for (var I = 0; I <str.length; I++)
{
var ch = str.substring(I, I + 1);
if (((ch <"a" || "z" <ch) && (ch <"A" || "Z" <ch)) && ch != ' ')
{
alert("\nThe NAME field only accepts letters
& spaces.\n\nPlease re-enter your name.");
document.forms[0].elements[0].select();
document.forms[0].elements[0].focus();
return false;
??? }
}
return true;
}
function isEmail()
{
emailAddress=document.forms[0].elements[1].value;
if (document.forms[0].elements[1].value == "") {
alert("\nThe E-MAIL field is blank.
\n\nPlease enter your e-mail address.")
document.forms[0].elements[1].focus();
return false;
}
if (document.forms[0].elements[1].value.indexOf ('@',0) == -1 ||
document.forms[0].elements[1].value.indexOf ('.',0) == -1)
{
alert("\nThe E-MAIL field requires a \"@\"
and a \".\"be used.\n\nPlease re-enter your e-mail address.")
document.forms[0].elements[1].select();
document.forms[0].elements[1].focus();
return false;
}
else
{
toName();
return true;
}
}
function isBrowser()
{
if (document.forms[0].elements[2].value !
= navigator.appName + " " + navigator.appVersion)
{
if (confirm("\nYou've changed your browser
type.\n\nClick on OK to keep changes.\
n\nClick on Cancel to restore detected browser."))
return true
else
{
document.forms[0].elements[2].value =
navigator.appName + " " + navigator.appVersion;
return true;??????
??? }
}
else
return true;
}
function isCountry() {
var str = document.forms[0].elements[3].value;
if (str == "") {
alert("\nThe COUNTRY field is
blank.\n\nPlease enter your country.")
document.forms[0].elements[3].focus();
return false;
}
for (var I = 0; I <str.length; I++) {
var ch = str.substring(I, I + 1);
if (((ch <"a" || "z" <ch) &&
(ch <"A" || "Z" <ch)) && ch != ' ')
{
alert("\nThe COUNTRY field only accepts
letters & spaces.\n\nPlease re-enter your country.");
document.forms[0].elements[3].select();
document.forms[0].elements[3].focus();
return false;
??? }
}
return true;
}
function isComment() {
if (document.forms[0].elements[4].value == "") {
if (confirm("\nYou're about to submit
without leaving a comment.\n\nClick
on CANCEL to include a comment.\n\nClick
on OK to continue without a comment."))
return true
else
{
document.forms[0].elements[4].focus();
return false;??????
}
}
else
return true???
}
function isFavorite() {
if (document.forms[0].elements[5].value == "") {
if (confirm("\nYou're about to submit without
listing your favorite sites.\n\nClick on CANCEL
to include favorites.\n\nClick on OK to continue
without listing favorites."))
return true
else
{
document.forms[0].elements[5].focus();
return false;??????
??? }
}
else
return true???
}
// End -->
</SCRIPT>