用javaScript實現(xiàn)表單驗證
Posted on 2008-11-25 19:14 wesley1987 閱讀(377) 評論(0) 編輯 收藏 所屬分類: struts學(xué)習(xí)項目**
* Check form
*/
function checkForm(vform){
for(var i=0;i<vform.elements.length;i++){
if(vform.elements[i].type=="text"){
var checkResult=checkTextBox(vform.elements[i]);
var name=vform.elements[i].getAttribute("name");
if(checkResult){
document.getElementById(name+"Msg").style.display="none";//alert(vform.elements.length+" - "+i+checkResult);
}
else{
document.getElementById(name+"Msg").style.display="inline";
vform.elements[i].focus();
return false;
}
}
}
return true;
}
/**//**
* Check text field in the form
*/
function checkTextBox(vTextBox){
var validChar=vTextBox.getAttribute("validChar");
var isRequired=vTextBox.getAttribute("isRequired");
var inputValue=vTextBox.value;
if(isRequired!="true" && inputValue.length<1){
return true;
}
else{
var regexStr=validChar;
var regex=new RegExp(regexStr);
return regex.test(inputValue);
}
}
/**//**
* Remove Extra Char in textbox
*/
function removeExtraChar(vTextBox,event){
var maxlength=parseInt(vTextBox.getAttribute("maxlength"));
var inputValue=vTextBox.value;
if(inputValue.length>=maxlength){
event.keyCode=9;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
對應(yīng)的JSP表單 :
<script src="<%=path%>/xxx.js" type="text/javascript"></script>
<form action="<%=path%>/addOffer.do" method="post" onsubmit="return checkForm(this);">
<table align="center" width="434" border="1">
<tr>
<td width="117">供應(yīng)商名稱(必填):</td>
<td width="300"><div align="left"> <input name="offername"
type="text"
maxlength="15"
height="16"
isRequired="true"
validChar="^[\u4E00-\u9FA5]{2,10}$" //用于驗證此text的正則表達式
onfocus="this.style.backgroundColor='#e6e6e6'"
onblur="this.style.backgroundColor='#ffffff'" />
<p id="offernameMsg" style="display:none">請輸入2-10位漢字</p>
</div>
</td>
</tr>
<tr>
<td width="117">地址:</td>
<td><div align="left"> <input name="offeradd"
type="text"
maxlength="20"
height="16"
validChar="^[\u4E00-\u9FA5\w]+$"
onfocus="this.style.backgroundColor='#e6e6e6'"
onblur="this.style.backgroundColor='#ffffff'"/>
<p id="offeraddMsg" style="display:none">請勿含特殊符號(含空格)</p>
</div></td></tr>
<tr>
<td>聯(lián)系人:</td>
<td><div align="left"> <input name="connecter" type="text" height="16"
maxlength="10"
validChar="^[\u4E00-\u9FA5\w]+$"
onfocus="this.style.backgroundColor='#e6e6e6'"
onblur="this.style.backgroundColor='#ffffff'"/>
<p id="connecterMsg" style="display:none">請勿含特殊符號(含空格)</p>
</div></td>
</tr>
</table></form>