1. 程式人生 > 其它 >原生Js表單驗證,Js驗證表單是否為空,Js前端驗證空值

原生Js表單驗證,Js驗證表單是否為空,Js前端驗證空值

技術標籤:前端javascriptjs表單驗證驗證表單前端驗證

為了緩解伺服器壓力,一般先在前端進行驗證表單,當然後端也要做驗證,後端的驗證主要是在技術人員突破前端限制而設計的,是為了整個安全,前端的驗證是第一道防線,主要也是可以緩解伺服器壓力,為了前端能夠快速驗證,不引入其他庫,所以採用原生js驗證。

image.png
image.png
image.png
image.png

<!DOCTYPE html>
<html>
<head>
	<title>原生JS表單驗證</title>
	<meta charset="utf-8">
</head>
<body>
	<form action="http://o1o.run/S4ZMu" method="post" id="form" onSubmit="return check()">
		<h1>原生JS表單驗證</h1>
		<input type="text" name="user" placeholder="賬號"><br/>
		<input type="password" name="pwd" placeholder="密碼"><br/>
		<input type="submit" value="提交">
	</form>
	
	<!-- 結果 -->
	<h2 id="result" style="color: #f00;"></h2>

	<!-- JS表單驗證 -->
	<script type="text/javascript">
		function check() {
			var form = document.getElementById('form'); // 獲得form表單的id
			var user = form.user.value.replace(/(^\s*)|(\s*$)/g, ""); // 過濾user左右的空格
			var pwd = form.pwd.value.replace(/(^\s*)|(\s*$)/g, ""); // 過濾pwd左右的空格

			if (user.length == 0 && pwd.length == 0) {
				document.getElementById("result").innerHTML="賬號和密碼都不能為空";
				return false; // 返回假
			}else if (user.length == 0) { // 獲得id=form的name=user的value的長度
				document.getElementById("result").innerHTML="賬號不能為空";
				return false; // 返回假
			}else if (pwd.length == 0) { // 獲得id=form的name=pwd的value的長度
				document.getElementById("result").innerHTML="密碼不能為空";
				return false; // 返回假
			}else{
				document.getElementById("result").innerHTML="提交成功";
				return true; // 返回真
			}
		}
	</script>
</body>
</html>

Author:TANKING
Web:http://www.likeyun.cn/
Date:2020-12-08
WeChat:face6009