JavaScript 可用來在數(shù)據(jù)被送往服務(wù)器前對 HTML 表單中的這些輸入數(shù)據(jù)進行驗證

站在用戶的角度思考問題,與客戶深入溝通,找到新北網(wǎng)站設(shè)計與新北網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都做網(wǎng)站、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名注冊、虛擬主機、企業(yè)郵箱。業(yè)務(wù)覆蓋新北地區(qū)。
JavaScript 表單驗證
JavaScript 可用來在數(shù)據(jù)被送往服務(wù)器前對 HTML 表單中的這些輸入數(shù)據(jù)進行驗證。
被 JavaScript 驗證的這些典型的表單數(shù)據(jù)有:
用戶是否已填寫表單中的必填項目?
用戶輸入的郵件地址是否合法?
用戶是否已輸入合法的日期?
用戶是否在數(shù)據(jù)域 (numeric field) 中輸入了文本?
必填(或必選)項目
下面的函數(shù)用來檢查用戶是否已填寫表單中的必填(或必選)項目。假如必填或必選項為空,那么警告框會彈出,并且函數(shù)的返回值為 false,否則函數(shù)的返回值則為 true(意味著數(shù)據(jù)沒有問題):
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
下面是連同 HTML 表單的代碼:
<html>
<head>
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
E-mail 驗證
下面的函數(shù)檢查輸入的數(shù)據(jù)是否符合電子郵件地址的基本語法。
意思就是說,輸入的數(shù)據(jù)必須包含 @ 符號和點號(.)。同時,@ 不可以是郵件地址的首字符,并且 @ 之后需有至少一個點號:
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
下面是連同 HTML 表單的完整代碼:
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false}
}
}
</script>
</head>
<body>
<form action="submitpage.htm"onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章名稱:JavaScript表單驗證實現(xiàn)代碼
URL網(wǎng)址:http://www.chinadenli.net/article8/pgdhip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、做網(wǎng)站、企業(yè)網(wǎng)站制作、Google、網(wǎng)站制作、網(wǎng)站設(shè)計公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)