代码如下:
/*************************
*
* Class:CheckItem
* 2009.08.23
**************************/
//-- Contructor
function CheckItem(textboxName,msgSpanId,validChar,isRequired){
this.textboxName=textboxName;
this.msgSpanId=msgSpanId;
this.validChar=validChar;
this.isRequired=isRequired;
}
/*************************
*
* Class:FormChecker
* 2009.08.23
**************************/
//-- Contructor
function FormChecker(){
this.checkItemArray=new Array;
}
//-- Add a check Item to array
FormChecker.prototype.addCheckItem=function(textboxName,msgSpanId,validChar,isRequired){
var checkItem=new CheckItem(textboxName,msgSpanId,validChar,isRequired);
this.checkItemArray[this.checkItemArray.length]=checkItem;
}
//-- Check text field in the form
FormChecker.prototype.checkTextBox=function(checkItem){
var validChar=checkItem.validChar;
var isRequired=checkItem.isRequired;
var inputValue=document.getElementById(checkItem.textboxName).value;
if(isRequired!="true" && inputValue.length<1){
return true;
}
else{
var regexStr="^"+validChar+"$";
var regex=new RegExp(regexStr);
return regex.test(inputValue);
}
}
//-- judge the validation a form
FormChecker.prototype.isValid=function(){
var toBeCheckedObjArray=this.checkItemArray;
for(var i=0;i<toBeCheckedObjArray.length;i++){
var toBeCheckedObj=toBeCheckedObjArray[i];
var checkResult=this.checkTextBox(toBeCheckedObj);
if(checkResult){
document.getElementById(toBeCheckedObj.msgSpanId).className="normalText";
}
else{
document.getElementById(toBeCheckedObj.msgSpanId).className="errorText";
document.getElementById(toBeCheckedObj.textboxName).focus();
return false;
}
}
return true;
}
验证效果如下:
初始化及验证的函数代码如下:
// --定义全局变量表单验证器
var formChecker;
window.onload=function(){
var stockTable=new MyTable("stockTable");
stockTable.refreshRowColor();
// 初始化表单验证器
formChecker=new FormChecker();
formChecker.addCheckItem("code","codeMsg","\\d{6}","true");
formChecker.addCheckItem("name","nameMsg","[\\u4E00-\\u9FA5]{3,4}","true");
formChecker.addCheckItem("price","priceMsg","\\d{2}[.]\\d{2}","true");
formChecker.addCheckItem("percent","percentMsg","\\d{1,2}[%]","true");
formChecker.addCheckItem("branch","branchMsg","[\\u4E00-\\u9FA5]{2,6}","true");
formChecker.addCheckItem("subBranch","subBranchMsg","[\\u4E00-\\u9FA5]{2,6}","true");
}
function appendRow(){
// 验证表单
if(formChecker.isValid()==false){
return;
}
}
当然,表单中不止文本框,但其他控件的验证相对简单,你可以在
formChecker.isValid()函数前后加上自己写的对这些控件的验证代码。
为完成高亮的效果,需要两个CSS类的支持:
.errorText{
color:#ff0000;
font-weight:bold;
}
.normalText{
color:#000000;
font-weight:normal;
}
全体代码下载,注意其中图片文件的相对位置:
http://www.blogjava.net/Files/heyang/JsTable20090823103043.rar
另外一个版本:
http://www.blogjava.net/Files/heyang/StockTable.rar