亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

javascript表單驗證大全

 更新時間:2015年08月12日 14:29:06   作者:u010220089  
JavaScript是用來在數(shù)據(jù)被傳輸?shù)椒?wù)前對html表單中輸入的數(shù)據(jù)進(jìn)行驗證,使用javascript對用戶輸入的信息進(jìn)行驗證是項目必須的,下面小編給大家整理一些比較常用的javascript表單驗證,需要的朋友可以參考下

被 JavaScript 驗證的這些典型的表單數(shù)據(jù)有以下幾種:

1.用戶是否已填寫表單中的必填項目?

2.用戶輸入的郵件地址是否合法?

3.用戶是否已輸入合法的日期?

4.用戶是否在數(shù)據(jù)域 (numeric field) 中輸入了文本?

下面是用戶名和密碼驗證代碼:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標(biāo)題文檔</title>
<script>
function validateForm()
{
 var username = document.forms["myForm"]["username"].value;
 var password = document.forms["myForm"]["password"].value;
 alert(username+" "+password);
}
</script>
</head>
<body>
<form name="myForm" action="" onSubmit=" return validateForm()" method="post">
用戶名:<input type="text" name="username"/><br/>
密碼:<input type="password" name="password"/><br/>
 <input type="submit" value="提交"/>
</form>
</body>
</html>

必填(或必選)項目驗證:

下面的函數(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>

以上代碼是用戶名、密碼、必填、必選項和email以及連同表單的代碼,希望對大家學(xué)習(xí)javascript表單驗證有所幫助。

相關(guān)文章

最新評論