使用JavaScript完成簡單的數據校驗


使用JS完成簡單的數據校驗

需求分析

使用JS完成對注冊頁面的簡單數據校驗,不允許出現用戶名或密碼為空的情況

技術分析

from表單屬性——onsubmit必須要有返回值,若為true,submit提交成功,若為false,無法提交

JS方法
.value:變量的值
.length:變量的長度
.test():檢驗括號內的值

正則表達式

代碼實現

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script>
			/*
				1. 確認事件: 表單提交事件 onsubmit事件 
				2. 事件所要觸發的函數: checkForm
				3. 函數中要干點事情
					1. 校驗用戶名, 用戶不能為空, 長度不能小於6位
						1.獲取到用戶輸入的值
			*/
			function checkForm(){
				//獲取用戶名輸入項
				var inputObj = document.getElementById("username");
				//獲取輸入項的值
				var uValue = inputObj.value;
//				alert(uValue);
				//用戶名長度不能6位 ""
				if(uValue.length < 6 ){
					alert("對不起,您的長度太短!");
					return false;	
				}
				//密碼長度大於6 和確認必須一致
				
				//獲取密碼框輸入的值
				var input_password = document.getElementById("password");
				var uPass = input_password.value;
				
				if(uPass.length < 6){
					alert("對不起,您還是太短啦!");
					return false;
				}
				
				//獲取確認密碼框的值
				var input_repassword = document.getElementById("repassword");
				var uRePass = input_repassword.value;
				if(uPass != uRePass){
					alert("對不起,兩次密碼不一致!");
					return false;
				}
				
				//校驗手機號
				var input_mobile = document.getElementById("mobile");
				var uMobile = input_mobile.value;
				//
				if(!/^[1][3578][0-9]{9}$/.test(uMobile)){
					
					alert("對不起,您的手機號無法識別!");
					
					return false;
				}
				
				//校驗郵箱: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				var inputEmail = document.getElementById("email");
				var uEmail = inputEmail.value;
				
				if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(uEmail)){
					alert("對不起,郵箱不合法");
					return false;
				}			
				return true;
			}	
		</script>
	</head>
	<body>
		<form action="JS開發步驟.html" onsubmit="return checkForm()">
			<div>用戶名:<input id="username" type="text"  /></div>
			<div>密碼:<input id="password" type="password"  /></div>
			<div>確認密碼:<input id="repassword" type="password"  /></div>
			<div>手機號碼:<input id="mobile"  type="number"  /></div>
			<div>郵箱:<input id="email" type="text"  /></div>
			<div><input type="submit" value="注冊"  /></div>
		</form>
	</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM