h5表单验证纯css示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>h5 form validate</title>
    <style>
        form{
            padding: 10px;
            margin: 0 auto;
        }
        form:focus-within:invalid{
            border: 1px solid red;
        }
        form:focus-within:invalid > .error {
            display: block;
        }
        .form-item{
            display: flex;
            margin-top: 10px;
        }
        label{
            cursor: pointer;
            width: 100px;
        }
        span{
            margin-top: 20px;
            width: 300px;
            border: 1px solid red;
            color: red;
            line-height: 30px;
            text-align: center;
            display: none;
        }
        input{
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid lightgray;
            width: 150px;
        }
        input:focus {
            outline: none;
        }
        input:focus:invalid,input:focus:out-of-range {
            border-color: red;
        }
        input:read-only {
            background-color: #eee;
        }
        input:read-write {
            border-color: lightblue;
        }
    </style>
</head>
<body>
    <form>
        <div class="form-item">
            <label for="name">姓名:</label>
            <input type="text" id="name" pattern="[a-z]\d\w*" required />
        </div>
        <div class="form-item">
            <label for="email">email地址:</label>
            <input type="email" id="email" />
        </div>
        <div class="form-item">
            <label for="num">数量:</label>
            <input id="num" type="number" min="0" max="10" />
        </div>
        <div class="form-item">
            <label for="depart">部门:</label>
            <input type="text" id="depart" readonly />
        </div>
        <span class="error">表单有错误</span>
    </form>
</body>
</html>

 常用的css验证伪类

in-range
:out-of-range
:placeholder-shown
::placeholder
:user-invalid
:invalid
:valid
:required
:optional

具体可参考: UI 伪类

posted @ 2023-05-17 17:08  全玉  阅读(20)  评论(0编辑  收藏  举报