<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span {
display: inline-block;
width: 250px;
height: 30px;
vertical-align: middle;
line-height: 30px;
padding-left: 15px;
}
.error {
color: red;
background: url(./images/error1.png) no-repeat left center;
}
.right {
color: green;
background: url(./images/right.png) no-repeat left center;
}
</style>
</head>
<body>
<input type="text">
<span></span>
<script>
// 规定正则表达式
const reg = /^[a-zA-Z0-9-_]{6,16}$/
// 获取元素
const input = document.querySelector('input')
const span = input.nextElementSibling
// 当表单失去焦点时开始验证
input.addEventListener('blur', function () {
if (reg.test(input.value)) {
span.innerHTML = '输入正确'
span.className = 'right'
} else {
span.innerHTML = '请输入6-16位的字母数字或-_'
span.className = 'error'
}
})
</script>
</body>
</html>
08-02
206

05-18