<!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>验证用户名案例</title>
<style>
span {
display: inline-block;
width: 250px;
height: 30px;
vertical-align: middle;
line-height: 30px;
padding-left: 15px;
}
.error {
color: red;
background: url(./error1.png) no-repeat left center;
}
.right {
color: green;
background: url(./right1.png) no-repeat left center;
}
</style>
</head>
<body>
<input type="text">
<span></span>
<script>
let input=document.querySelector('input');
let span=input.nextElementSibling;
input.addEventListener('blur',function(){
if(/^[a-zA-Z0-9-_]{6,16}$/.test(input.value)){
span.className='right';
span.innerHTML='输入正确';
}else{
span.className='error';
span.innerHTML='用户名输入不合法!';
}
})
</script>
</body>
</html>
这是一个使用JavaScript进行用户名验证的示例。当输入框失去焦点时,通过正则表达式检查用户名是否符合要求,6到16个字母、数字、下划线和破折号的组合。如果符合规则,显示绿色的正确提示;否则,显示红色错误提示。
776

被折叠的 条评论
为什么被折叠?



