JavaScript 可用來在數(shù)據(jù)被送往服務(wù)器前對(duì) HTML 表單中的這些輸入數(shù)據(jù)進(jìn)行驗(yàn)證。
壞數(shù)據(jù)不該抵達(dá)服務(wù)器:提交表單時(shí)的驗(yàn)證.
表單域?qū)ο罄镉袀€(gè)form特性,它使用數(shù)組表示了整份表單的域.
假如這里只有一個(gè)簡(jiǎn)單的信息文本框和一個(gè)郵政編碼框,還有一個(gè)提交按鈕.
<form>
<input id="message" name="message" type="text" size="12" onBlur="validate_Length(1,32,this,document.getElementById('message_help'));" />
<message_help" class="help"></span>
<input id="ZipCode" name="phone" type="text" size="5" onBlur="validate_ZipCode(this,document.getElementById('ZipCode_help'));" />
<span id="ZipCode_help" class="help"></span>
<input type="button" value="Order Banner" onClick="placeOrder(this.form);"/>
</form>
<script language="javascript" type="text/javascript">
//文本長(zhǎng)度驗(yàn)證
function validate_Length(minLegth,maxlength,inputFiled,helpText)
{
if(inputFiled.value.length<minLegth||inputFiled.value.length>maxlength)
{
if(helpText!=null)
{
helpText.innerHTML="請(qǐng)輸入長(zhǎng)度為"+minLenght+"到"+maxLength+"的文本";
return false;
}
}
else if(helpText!=null)
{
helpText.innerHTML=""
return true;
}
}
//郵政編碼驗(yàn)證
function validate_ZipCode(inputFiled,helpText)
{
if(inputFiled.value.length!=5)
{
if(helpText!=null)
helpText.innerHTML="郵政編碼長(zhǎng)度必須為5位";
return false;
}
else if(isNaN(inputFiled.value))
{
if(helpText!=null)
helpText.innerHTML="郵政編碼必須為數(shù)字";
return false;
}
else if(helpText!=null)
{
helpText.innerHTML=""
return true;
}
}
function placeOrder(form)
{
if(validateNonEmpty(1,32,form["phone"],form["phone_help"])&&validate_ZipCode(form["ZipCode"],form["ZipCode_help"]))
{
form.submit();
}
else{
alert("您填寫的表單數(shù)據(jù)至少有一項(xiàng)不合法");
}
}
</script>
總結(jié):只需要調(diào)用相應(yīng)的驗(yàn)證函數(shù),得到返回值,便可在最后提交表單的時(shí)候完成最后的數(shù)據(jù)過濾
在實(shí)際應(yīng)用中,往往需要對(duì)數(shù)據(jù)的長(zhǎng)度,非空,非法字符,格式,大小定等等做驗(yàn)證,這里不一一介紹,重在領(lǐng)會(huì)。
好了,有關(guān)Javascript的表單驗(yàn)證-提交表單的相關(guān)知識(shí),小編就給大家介紹到這里,希望對(duì)大家有所幫助!