js策略模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
form {
width: 500px;
margin: 0 auto;
height: 200px;
padding: 20px 0;
}
.item {
height: 80px;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.item label {
flex-basis: 100px;
}
.item input {
flex-basis: 400px;
box-sizing: border-box;
}
.item span {
flex-basis: 500px;
font-size: 12px;
text-align: center;
height: 30px;
}
</style>
</head>
<body>
<form>
<div class="item">
<label>用户名</label> <input id="usernameInput" type="text" /> <span id="usernameTips"></span>
</div>
<div class="item">
<label>密码</label> <input id="passwordInput" type="password" /> <span id="passwordTips"></span>
</div>
</form>
<script>
var usernameInput = document.getElementById("usernameInput");
var usernameTips = document.getElementById("usernameTips");
var passwordInput = document.getElementById("passwordInput");
var passwordTips = document.getElementById("passwordTips");
var Strategy = (function() {
var _S = {
checkWord7T19(value) {
var checkWord7T19 = /^[a-zA-Z_]\w{6,18}$/;
return checkWord7T19.test(value) ? "" : "请输入长度为7~19位的组合字符,由数字、字母、下划线组成,不能以数字开头"
},
checkWord7T16(value) {
var checkWord7T16 = /^[a-zA-Z_]\w{6,15}$/;
return checkWord7T16.test(value) ? "" : "请输入长度为7~16位的组合字符,由数字、字母、下划线组成,不能以数字开头"
}
}
return {
add(name, fn) {
_S[name] = fn;
},
use(name, value) {
return _S[name](value)
}
}
})();
Strategy.add("checkemail", function(value) {
var reg = /^\w{1,20}@\w{2,5}\.\w{2,4}$/;
return reg.test(value) ? "" : "请输入格式正确的邮箱";
});
usernameInput.onblur = function() {
var str = Strategy.use("checkemail", this.value);
if (str) {
usernameTips.innerHTML = str;
usernameTips.style.color = "red";
return;
}
usernameTips.style.color = "green";
usernameTips.innerHTML = "√";
}
passwordInput.onblur = function() {
var str = Strategy.use("checkWord7T19", this.value);
if (str) {
passwordTips.innerHTML = str
passwordTips.style.color = "red";
return;
}
passwordTips.style.color = "green";
passwordTips.innerHTML = "√";
}
</script>
</body>
</html>