表单输入字段pattern属性配合checkValidity方法实现表单验证

<!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>
        *{
            margin:0;
            padding:0;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            box-sizing:border-box;
        }
        
        .green {
            color: green;
        }
        
        .red {
            color: red;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <th>用户名</th>
            <td><input type="text" pattern="^[a-zA-Z0-9_-]{4,16}$" data-name="用户名"></td>
            <td><span></span></td>
        </tr>
        <tr>
            <th>密码</th>
            <!-- pattern属性 为input设置正则表达式,配合checkValidity方法验证 -->
            <td><input type="password" pattern="^\w{6,13}$" data-name="密码"></td>
            <td><span></span></td>
        </tr>
    </table>
    <script>
        const ipts = document.querySelectorAll('input');
        const spans = document.querySelectorAll('span');
        let colorFlag = true; //判断颜色
        ipts.forEach((input, index) => {
            input.onblur = function() {
                let iptType = this.getAttribute('data-name');
                if (this.value) {
                    //checkValidity()是表单对象方法,用于验证输入是否合法
                    if (this.checkValidity()) {
                        spans[index].innerText = `${iptType}合法`;
                        colorFlag = true;
                    } else {
                        spans[index].innerText = `${iptType}不合法`;
                        colorFlag = false;
                    }
                } else {
                    spans[index].innerText = `请输入${iptType}`;
                    colorFlag = false;
                }
                spans[index].className = colorFlag ? 'green' : 'red';
            }
        })
    </script>
</body>

</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值