1. 程式人生 > >javascript實現文本框標簽驗證

javascript實現文本框標簽驗證

line rop charset NPU 焦點 this ctype html eight

< !DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-8" > <title > Document < /title>
</head > <style type = "text/css" > body {
background: #ccc;
}
label {
width: 100px;
display: inline - block;
}
span {
color: red;
}.container {
margin: 100px auto;
width: 400px;
padding: 50px;
line - height: 40px;
}
span {
margin - left: 30px;
font - size: 12px;
} < /style>
<body>
<div class="container">
<label>姓名不能為空</label > <input type = "text"id = "inp1" > <span > </span><br/ > <label > phone不能為空 < /label><input type="text" id="inp2"><span></span > <br / ></div>
<script>
/ / 失去焦點後判斷用戶輸入是否為空
var inp1 = document.getElementById("inp1");
inp1.onblur = function() {
if (trim(this.value) === "") {
alert("輸入不能為空");
} else {
alert("輸入正確");
}
};

function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
}

var inp2 = document.getElementById("inp2");
inp2.onblur = function(e) {
if (inp2.value == "4444") {
alert("正確");
e.stopPropagation();
} else {
alert("錯誤")
}
}; < /script>
</body > </html>/

javascript實現文本框標簽驗證