原生js驗證表單


html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表單</title>
<link rel="shortcut icon" type="image/x-icon" href="../img/ic.png"/>
<link rel="stylesheet" href="../css/form.css"/>
<script src="../js/vailidate.js"></script>
</head>
<body>
<h1>用戶注冊</h1>
<form action="demo1.html" method="post" enctype="multipart/form-data" class="register">
<!-- 用戶名 -->
<div>
<label for="userName">用戶名</label>
<input placeholder="輸入用戶名" type="text" name="userName" class="userName" id="userName"/>
<span>*</span>
</div>
<input type="hidden" name="id" value="1"/>
<!-- 密碼 -->
<div>
<label for="password">密碼</label>
<input type="password" name="password" id="password" class="password" placeholder="輸入密碼"/>
<span>*</span>
</div>
<div>
<label for="realName">真實姓名</label>
<input placeholder="輸入用戶名" type="text" name="realName" class="realName" id="realName"/>
<span>*</span>
</div>
<!-- 性別單選框 -->
<div>
<label>性別</label>
<input type="radio" name="gender" value="男" checked/><input type="radio" name="gender" value="女"/><span> </span>
</div>
<!-- 愛好復選框 -->
<div>
<label>愛好</label>
<input type="checkbox" name="hobby" value="LOL"/>LOL
<input type="checkbox" name="hobby" value="王者"/>王者
<input type="checkbox" name="hobby" value="吃雞" checked/>吃雞
<input type="checkbox" name="hobby" value="飛車"/>飛車
<span id="afterHobby">*</span>
</div>
<!-- 生日 -->
<div>
<label for="birthday">生日</label>
<input type="date" id="birthday" class="birthday" name="birthday"/>
<span>*</span>
</div>
<!-- 身份證 -->
<div>
<label for="identityNo">身份證號</label>
<input type="text" id="identityNo" class="identityNo" name="identityNo" placeholder="輸入身份證"/>
<span>*</span>
</div>
<!-- 電話 -->
<div>
<label for="phone">電話</label>
<input type="tel" id="phone" name="phone" class="phone" placeholder="輸入電話"/>
<span>*</span>
</div>
<!-- 郵箱 -->
<div>
<label for="email">郵箱</label>
<input type="email" id="email" name="email" class="email" placeholder="輸入郵箱"/>
<span>*</span>
</div>
<!-- 個人評價 -->
<div class="resume">
<label for="resume">個人評價</label>
<textarea id="resume" cols="20" rows="10" style="vertical-align: middle;"></textarea>
<span>*</span>
</div>
<!-- 城市 -->
<div>
<label>所屬城市</label>
<select id="province" name="province">
<option value="ah">安徽</option>
<option value="zj">浙江</option>
<option value="js" selected>江蘇</option>
<option value="jx">江西</option>
</select><select id="city" name="city">
<option value="hf">合肥</option>
<option value="hz">杭州</option>
<option value="nj" selected>南京</option>
<option value="nc">南昌</option>
</select><select id="district" name="district">
<option value="bh">濱湖</option>
<option value="xh">西湖</option>
<option value="jy" selected>建鄴</option>
<option value="lcq">老城</option>
</select></div>
<!-- 頭像 -->
<div>
<label for="random">驗證碼</label>
<input id="random" type="text" class="random" name="random" disabled/>
<input id="reRandom" type="text" class="reRandom" name="reRandom"/>
<span>*</span>
</div>
<!-- 頭像 -->
<div>
<label for="pic">頭像</label>
<input id="pic" type="file" name="pic"/>
<span>*</span>
</div>
<!-- 提交和重置 -->
<div>
<label> </label>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</div>
</form>
</body>
</html>
<style>

 

style:

body {
background: url("1000357.jpg") no-repeat;
background-size: cover;
}

.register {
width: 60%;
margin: 0 auto;
background-color: rgba(132, 170, 241, 0.2);
padding: 10px;
border-radius: 5px;

}

div {
margin: 10px;
height: 30px;
}

label {
width: 80px;
display: inline-block;
text-align-last: justify;
margin-right: 10px;
}

.userName,
.password,
.birthday,
.phone,
.email,
.identityNo,
.realName {
height: 24px;
width: 280px;
padding-left: 10px;
}

.random, .reRandom {
height: 24px;
width: 130px;
padding-left: 10px;
text-align: center;
}


#resume {
width: 288px;
}

.resume {
height: 150px;
margin-bottom: 20px;
}

select {
height: 28px;
}

[type="submit"], [type="reset"] {
border: none;
width: 100px;
text-align: center;
background-color: green;
color: white;
line-height: 30px;
height: 30px;
border-radius: 5px;
}

.register span {
color: red;
}

h1 {
margin: 0 auto;
padding: 0;
color: #7f6b6b;
width: 60%;
}

 

script:

/**
*使用String類和正則表達式進行表單驗證
*/
//隨機驗證碼
let num = "";
//頁面加載結束執行的函數
onload = function () {
blurElement();
submitForm();
//愛好的change事件驗證選擇結果
let hobbyArr = document.querySelectorAll("input[name='hobby']");
for (let i = 0; i < hobbyArr.length; i++) {
hobbyArr[i].onchange = function () {
vailidateHobby();
};
}

//驗證圖片
document.getElementById("pic").onchange = function () {
vailidatePic();
};

//產生隨機驗證碼
generateRandomNum();
};

//元素失去焦點時執行的驗證函數
function blurElement() {
//驗證用戶名
document.getElementById("userName").onblur = function () {
vailidateUserName();
};

//驗證密碼
document.getElementById("password").onblur = function () {
vailidatePassword()
};

//驗證真實姓名
document.getElementById("realName").onblur = function () {
vailidateRealName();
};

//驗證生日
document.getElementById("birthday").onblur = function () {
vailidateBirthday();
};

//驗證電話
document.getElementById("phone").onblur = function () {
vailidatePhone();
};

//驗證郵箱
document.getElementById("email").onblur = function () {
vailidateEmail();
};

//驗證簡介
document.getElementById("resume").onblur = function () {
vailidateResume();
};

//驗證id
document.getElementById("identityNo").onblur = function () {
vailidateID();
};
}

//表單提交執行的函數
function submitForm() {
let form = document.getElementsByClassName("register")[0];
form.onsubmit = function (e) {
//e.preventDefault();
let flag =
vailidateUserName()
& vailidateHobby()
& vailidatePassword()
& vailidateRealName()
& vailidateBirthday()
& vailidatePhone()
& vailidateEmail()
& vailidateResume()
& vailidatePic()
& vailidateID();
//alert(flag);
return flag == 1 ? true : false;
};
}

//1、驗證用戶名:6-12位,字母開頭,不能有_$之外的特殊字符,非空,唯一
function vailidateUserName() {
let username = document.getElementById("userName");
let span = next(username);
let value = username.value;
let reg = /^[a-zA-Z][\w$]{5,11}$/;
if (value == "") {
span.innerHTML = "用戶名不能為空";
span.style.color = "red";
return false;
} else if (!reg.test(value)) {
span.innerHTML = "用戶名6-12位字母開頭";
span.style.color = "red";
return false;
}
span.innerHTML = "用戶名可用";
span.style.color = "green";
return true;
}

//2、驗證密碼:6-12位非空,必須包含大寫字符,字母開頭,非空
function vailidatePassword() {
let password = document.getElementById("password");
let span = next(password);
let value = password.value;
let code = /^[a-zA-Z]$/;
//非空
if (value == "") {
span.innerHTML = "密碼不能為空";
span.style.color = "red";
return false;
}
//首字母
let firstWord = value.charAt(0);
if (!code.test(firstWord)) {
span.innerHTML = "密碼首位必須是字母";
span.style.color = "red";
return false;
}
//大寫字符 hello
let upCode = /^[A-Z]$/;
for (let i = 0; i < value.length; i++) {
if (upCode.test(value[i])) {
break;
} else if (i == value.length - 1) {
span.innerHTML = "密碼必須必須包含一位大寫字母";
span.style.color = "red";
return false;
}
}
//長度
if (value.length > 12 || value.length < 6) {
span.innerHTML = "密碼長度6-12位";
span.style.color = "red";
return false;
}
span.innerHTML = "密碼可用";
span.style.color = "green";
return true;
}

//3、驗證愛好:至少一個
function vailidateHobby() {
let hobbyArr = document.querySelectorAll("input[name='hobby']");
let count = 0;
for (let i = 0; i < hobbyArr.length; i++) {
if (hobbyArr[i].checked) {
count++;
}
}
let span = document.getElementById("afterHobby");
if (count == 0) {
span.innerHTML = "愛好至少選擇一個";
span.style.color = "red";
return false;
}
span.innerHTML = "愛好選擇正確";
span.style.color = "green";
return true;
}

//4、驗證生日,非空
function vailidateBirthday() {
let birthday = document.getElementById("birthday");
let span = next(birthday);
let value = birthday.value;
//2019-09-10
console.log(value);
//非空
if (value == "") {
span.innerHTML = "生日不能為空";
span.style.color = "red";
return false;
}
span.innerHTML = "生日正確";
span.style.color = "green";
return true;
}

//5、驗證電話 1[3456789]\d{9}
function vailidatePhone() {
let phone = document.getElementById("phone");
let span = next(phone);
let value = phone.value;
let reg = /^1[3456789]\d{9}$/;
if (value == "") {
span.innerHTML = "電話不能為空";
span.style.color = "red";
return false;
}
if (value.charAt(0) !== '1') {
span.innerHTML = "電話首位是1";
span.style.color = "red";
return false;
}
if (!(/^[3456789]$/.test(value.charAt(1)))) {
span.innerHTML = "電話第2位是3456789任一位";
span.style.color = "red";
return false;
}
if (!reg.test(value)) {
span.innerHTML = "電話11位數字";
span.style.color = "red";
return false;
}
span.innerHTML = "電話正確";
span.style.color = "green";
return true;
}

//6、驗證郵箱 hao123@qq.com /hao123@qq.com.cn /hao123@qq.cn /hao123@qq.org /hao123@qq.net
function vailidateEmail() {
let email = document.getElementById("email");
let span = next(email);
let value = email.value;
let reg = /^[A-Za-z]\w+@[a-z0-9]{2,}(\.com|\.cn|\.com\.cn|\.net|\.org)$/;
if (value == "") {
span.innerHTML = "郵箱不能為空";
span.style.color = "red";
return false;
} else if (!reg.test(value)) {
span.innerHTML = "郵箱不合法,請參考:hao123@qq.com.cn";
span.style.color = "red";
return false;
}
span.innerHTML = "郵箱正確";
span.style.color = "green";
return true;
}

//7、驗證個人評價 不能超200字,非空
function vailidateResume() {
let resume = document.getElementById("resume");
let span = next(resume);
let value = resume.value;
if (value == "") {
span.innerHTML = "個人評價不能為空!";
span.style.color = "red";
return false;
}
if (value.length > 200) {
span.innerHTML = "內容不能超200字符!";
span.style.color = "red";
return false;
}
span.innerHTML = "輸入正確!";
span.style.color = "green";
return true;
}

//8、驗證頭像(大小和類型)
function vailidatePic() {
//let arr = ["png", 'jpg', 'gif', 'bmp'];
let pic = document.getElementById("pic");
let span = next(pic);
let reg = /^png|jpg|gif|bmp$/;
//獲得當前圖片的文件列表,是一個數組
let fileList = pic.files;
console.log(fileList);
let imgFile = fileList[0];
//必須處理的undefined異常
if (!imgFile) {
span.innerHTML = "文件沒有上傳文件";
span.style.color = "red";
return false;
}
//獲得imgFile的3個屬性
let fileName = imgFile.name;//expo.png
let fileSize = imgFile.size;//字節 1024byte = 1kB,1024kB = 1M
//文件名的后綴
let suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//png
if (fileSize > (150 * 1024)) {
span.innerHTML = "文件大小不能超150KB";
span.style.color = "red";
return false;
} else if (!reg.test(suffix)) {
span.innerHTML = "文件必須是圖片格式";
span.style.color = "red";
return false;
}
span.innerHTML = "文件正確";
span.style.color = "green";
return true;
}

//9、驗證身份證號碼 18位
function vailidateID() {
let id = document.getElementById("identityNo");
let span = next(id);
//53 0102 1920 05 08 011X
let value = id.value;
//判斷空
if (value == "") {
span.innerHTML = "身份證號碼不能為空";
span.style.color = "red";
return false;
}
//判斷長度
if (value.length != 18) {
span.innerHTML = "身份證號碼長度18位";
span.style.color = "red";
return false;
}
//判斷前17位數字
let reg = /^\d{17}$/;
let str = value.substring(0, 17);
if (!reg.test(str)) {
span.innerHTML = "身份證號碼前17位必須是數字";
span.style.color = "red";
return false;
}
//判斷驗證碼
reg = /^[\dxX]$/;
str = value.substring(17);
if (!reg.test(str)) {
span.innerHTML = "驗證碼必須是數字、x、X";
span.style.color = "red";
return false;
}
//判斷區域碼
let arr = [
"11", "12", "13", "14", "21", "22", "23",
"21", "22", "23",
"31", "32", "33", "34", "35", "36", "37",
"41", "42", "43", "44", "45", "46",
"50", "51", "52", "53", "54",
"61", "62", "63", "64", "65",
"81", "82", "83"
];
str = value.substring(0, 2);
for (let i = 0; i < arr.length; i++) {
if (str === arr[i]) {
break;
} else if (i == arr.length - 1) {
span.innerHTML = "區域碼不正確!";
span.style.color = "red";
return false;
}
}
//判斷年 [1900-now]
let year = parseInt(value.substring(6, 10));
let now = new Date().getFullYear();
if (year > now || year < 1900) {
span.innerHTML = "年份必須在1900-" + now + "之間";
span.style.color = "red";
return false;
}
//判斷月 [1-12]
let month = parseInt(value.substring(10, 12));
if (month > 12 || month < 1) {
span.innerHTML = "月份必須在1-12之間!";
span.style.color = "red";
return false;
}
//判斷日 [1-28][1-29][1-30][1-31]
let days = 0;
//2月的天數,根據year是否閏年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
//閏年
days = 29;
} else {
//平年
days = 28;
}
let arrDays = [31, days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let date = parseInt(value.substring(12, 14));
if (date < 1 || date > arrDays[month - 1]) {
span.innerHTML = "日必須在1-" + arrDays[month - 1] + "之間";
span.style.color = "red";
return false;
}
span.innerHTML = "身份證號碼正確";
span.style.color = "green";
return true;
}

//10、驗證真實姓名:漢字[2,50]|字母[3-50]
function vailidateRealName() {
let realName = document.getElementById("realName");
let span = next(realName);
let value = realName.value;
let reg = /^([\u4e00-\u9fa5]{2,50})|([A-Za-z]{3,50})$/;
if (value == "") {
span.innerHTML = "真實姓名不能為空";
span.style.color = "red";
return false;
} else if (!reg.test(value)) {
span.innerHTML = "真實姓名漢字[2,50]或者字母[3-50]";
span.style.color = "red";
return false;
}
span.innerHTML = "姓名可用";
span.style.color = "green";
return true;
}

//驗證隨機驗證碼
function vailidateRandom () {
//作業:完成今天所有表單驗證
//還有此處驗證功能:just do it!
}

//t元素后面的兄弟元素
function next(t) {
return t.nextElementSibling;
}

//產生隨機驗證碼
function generateRandomNum() {
for (let i = 0; i < 6; i++) {
num += parseInt(Math.random() * 10);
}
document.getElementById("random").value = num;
}

 



 

 


免責聲明!

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



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