验证输入框是否在要求的位数之间, 否则高亮且无法提交

<!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>
        .bg {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <input type="text" id="name"><br>
    <input type="button" value="提交" id="btn">
    
    <script>
        //检测用户名是否是3-6位, 如果不满足要求高亮显示文本框
        var btn = document.getElementById("btn");
        var username = document.getElementById("name");

        btn.onclick = function(){
            //判断用户名
            if(username.value.length < 3 || username.value.length > 6){
                username.className = "bg";
            }
            else {
                username.className = "";
            }
        };
    </script>
</body>
</html>
posted @ 2021-08-12 21:31  charonmomo  阅读(28)  评论(0编辑  收藏  举报