HTML5 基础(4)—— HTML5表单新属性的使用和验证表单

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39141044/article/details/80721154

一、HTML5表单常用属性

这些都是比较常用的

属性名 说明
placeholder 在输入框无内容时显示灰色提示
autocomplete 部分输入框和form都可以设置自动提示 off关闭,on开启(默认是on)
autofocus 让input自动获取焦点
required 设置表单元素为必填
pattern 表单验证使用正则
novalidate 该属性使用在form标签上,让设置了验证的表单可以直接提交 <form action=”…” novalidate>…</form>
formnovalidate 该属性使用在提交按钮上,让设置了验证的表单可以直接提交 <input type=”submit” value=”提交” formnonvalidate />
for <label>的for属性是要配合<input>标签中的id属性使用的,点击label标签for对应id的input标签会获取焦点


(一)部分类型的input无法使用placeholder属性提示的解决方案

如输入日期

<input type="text" name="date" onfocus="(this.type='date')" placeholder="请输入日期"/>

这里写图片描述
点击后
这里写图片描述
缺点是需要用户点击2次

(二)<label>的for属性使用

    <label for="man">男</label>
    <input type="radio" id="man" name="sex" />
    <label for="woman">女</label>
    <input type="radio" id="woman" name="sex" />
    <br>
    <label for="username">用户名</label>
    <input type="text" name="username" id="username" placeholder="请输入用户名" />

这里写图片描述
点击文字选中单选按钮

二、html5表单元素约束验证API

属性/方法/对象 说明
willValidate属性 元素元素有没有被符合。没有符合返回false
validity对象 元素当前验证状态(对象)
validationMessage属性 描述与元素相关约束的失败信息
checkValidity()方法 元素是否满足任意约束
setCustomValidity()方法 设置自定义的验证信息


(一)validity对象的属性

<form action="#">
    <input type="text" name="username" id="username" placeholder="请输入用户名" required pattern="^\d{4}$" />

    <input type="submit"/>
</form>
<script type="text/javascript">
    var input_username = document.getElementById('username');
    console.log(input_username.validity);
</script>

控制台会打印出
这里写图片描述

属性名 说明
valid:true/false 当前输入是否有效
badInput: false/true 输入的值是否无效
patternMismatch: false/true 正则表达式验证失败
rangeOverflow: false/true 输入值是否超过max的限定
rangeUnderflow: false/true 输入值是否小于min的限定
tooLong : false/true 输入的字符数是否超过maxlength
tooShort : false/true 输入的字符数是否小于minlength
stepMismatch : false/true 输入的数字不符合step限制
typeMismatch : false/true 输入值不符合email、url的验证
valueMissing : false/true 未输入值,违反了required要求
customError : false/true 是否存在自定义错误
  • 只要有一个验证方面错误,某个属性就为true,valid值为false
  • 只有没有任何验证错误,所有的属性都为false,valid才能为true
  • 上述的每个错误在浏览器内部都有一个预定义的错误提示消息
  • 所有的错误消息中,只要存在“自定义的错误消息”,浏览器只显示自定义的错误消息,优先级高于浏览器预定义的错误消息(设置自定义错误消息用setCustomValidity())

  • 当前没有自定义错误消息,所以customError : false

获取与约束相关的属性

validity对象中的每一个属性代表一个验证状态,false表示验证没问题,true表示不符合验证

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <form action="" method="get" id="forms">
            <input type="text" id="username" placeholder="用户名" required />
            <input type="password" id="pws" placeholder="密码" required />
            <input type="email" id="email" placeholder="邮箱" required />
            <input type="submit" value="提交" id="submitBtn">
        </form>
        <script>
            var form = document.getElementById("forms"),
            submitBtn = document.getElementById("submitBtn");

            submitBtn.addEventListener("click", function() {
                var invalidFields = form.querySelectorAll(":invalid");
                for(var i=0,len=invalidFields.length;i<len;++i){
                    console.log('input#'+invalidFields[i].id+':'+invalidFields[i].validationMessage);
                }
            });
        </script>
    </body>
</html>

:invalid表示无效,即当填写的内容不符合要求的时候触发,form.querySelectorAll(“:invalid”);表示查询表单失效的元素。
这里写图片描述

(二)checkValidity()方法(常用)

一个input有许多约束条件,只有都满足了,才返回true,只要有任意一个约束条件不满足就返回false

<body>
    <form action="">
        <input type="text" id="username" value="" required pattern="^\d{}">
    </form>
    <script>
        var names = document.getElementById("username");
        if(names.checkValidity()){
            alert("符合验证条件");
        }else{
            alert("不符合验证条件");
        }
    //或者
        if(username.checkValidity()){
            alert("符合验证条件");
        }else{
            alert("不符合验证条件");
        }
    </script>
</body>

PS:
在HTML5中,js中一个元素的id就代表该元素的dom元素

document.getElementById("username")===username //值为true

不过不建议这样用,容易和变量混淆。

setCustomValidity()方法(常用)

设置自定义的验证提示信息,用于根据validity对象中的验证约束来覆盖预定义的信息。

<body>
    <form action="" method="get">
        <input type="url" oninput="checkit(this)">
        <input type="submit" value="提交">
    </form>
    <script>
        function checkit(obj) {
            var it = obj.validity;
            if(it.typeMismatch === true){
                obj.setCustomValidity("请输入带http://的网站");
            }
        }
    </script>
</body>

这里写图片描述

三、HTML5<input>标签部分类型的限制和去除默认样式

(一)input[type=search]

1.去除默认按钮

这里写图片描述

<head>
<meta charset="UTF-8" />
<style>
    input[type="search"]::-webkit-search-cancel-button{
        -webkit-appearance:none; //去除浏览器的默认样式
        height: 12px;
        width: 12px;
        background-color: red;
    }
</style>
</head>
<body>
    <form action="#">
    <input type="search" name="search" id="search" />
    <br>
    <br>
    <input type="submit"/>
    </form>
</body>

去除浏览器默认样式并自定义
这里写图片描述

(二)input[type=number]

1.去除默认的上下按钮

这里写图片描述

<style>
    input[type="number"]::-webkit-inner-spin-button{
        -webkit-appearance:none;
    }
</style>
</head>
<body>
    <form action="#">
    <input type="number" name="number" id="number" placeholder="请输入数字" />
    <br>
    <br>
    <input type="submit"/>
    </form>
</body>

这里写图片描述

2.限制input[type=number]输入内容的长度

input[type=number]无法像input[type=text]那样使用maxlength属性来限制输入内容的最大长度。

<input type="number" name="number" id="number" maxlength="4" placeholder="请输入数字" />

这里写图片描述

解决方法:
使用js控制

<style>
    input[type="number"]::-webkit-inner-spin-button,
    input[type="number"]::-webkit-outer-spin-button{
        -webkit-appearance:none;
    }
</style>
</head>
<body>
    <form action="#">
    <input type="number" name="number" id="number" oninput="checkLength(this,4)" placeholder="请输入数字" />
    <br>
    <br>
    <input type="submit"/>
    </form>
    <script type="text/javascript">
        function checkLength(obj,length){
            if(obj.value.length>length){
                obj.value = obj.value.substr(0,length);
            }
        }
    </script>
</body>

这里写图片描述

3.输入的内容保留小数

<input type="number" name="number" step="0.01" id="number" oninput="checkLength(this,4)" placeholder="请输入数字" />

step=”0.01”保留2位小数
step=”0.001”保留3位小数

四、使用伪类选择器对HTML5表单进行美化

常用的伪类选择器有:

伪类 说明 伪类 说明
:required 选择所有必填表项 :optional 选择所有选填项
:in-range 选择值符合min和max约束的项 :out-of-range 选择值不符合min和max约束的项
:valid 选择符合所有约束的项 :invalid 选择有约束不符合的项
:read-only 选择只读的项 :read-write 选择可编辑的(包括含有contenteditable属性)的项

(一):required 和 :optional 美化表单

这里会用到::before和::after伪元素
伪元素简单案例

.tip{
    margin-top: 30px;
}
.tip>span{
    position: relative;
    display: inline-block;
}
.tip>span:hover{
    cursor: pointer;
}
.tip>span:hover::before{
    content: attr(data-info);
    position: absolute;
    margin-left: 8px;
    padding: 10px;
    background-color: #aa0088;
    color: #FFF;
    left: 100%;
    top: -60%;
    white-space: pre; 
}
.tip>span:hover::after{
    content: '';
    position: absolute;
    width: 0;
    height: 0;
    border-right: 8px solid #aa0088;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
}
<div class="tip">
    <span data-info="这是提示内容">鼠标悬浮显示提示</span>
</div>

表单美化案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>:required和:optional美化表单</title>
    <style>
        *{margin: 0;padding: 0;}
        .container{width: 400px;margin: 30px auto;}
        input,select,textarea{
            width: 240px;
            margin: 10px 0;
            border:1px solid #999;
            padding: .5em 1em;
        }
        input:focus,select:focus,textarea:focus{
            outline: 0;
        }
        label{color: #999;margin-left: 30px;}

        /*必填项*/
        input:required,textarea:required{
            border-right: 3px solid #FF3030;
        }
        input:required:focus,textarea:required:focus{
            box-shadow: 0 0 3px 1px #FF3030;
        }
        input:required+label::after{
            content: "(必填)";
        }
        /*选填项*/
        input:optional,select:optional{
            border-right: 3px solid #66ccff;
        }
        input:optional:focus,select:optional:focus{
            box-shadow: 0 0 3px 1px #66ccff;    
        }
        input:optional+label::after{
            content: "(选填)";
        }

        input[type="submit"]{
            background-color: #FF3030;
            border: 3px solid #FF3030;
            color: #FFF;
        }
        input[type="submit"]:hover{
            background-color: #FF0000;
        }
    </style>
</head>
<body>
    <div class="container">
        <form action="#">
            <input type="text" name="username" required /><label>用户名</label>
            <input type="email" name="email" required /><label>邮箱</label>
            <input type="tel" name="tel"><label>手机号</label>
            <input type="url" name="url"><label>网址</label>
            <select name="aihao">
                <option value="0">非必填选项1</option>
                <option value="1">非必填选项2</option>
                <option value="2">非必填选项3</option>
                <option value="3">非必填选项4</option>
                <option value="4">非必填选项5</option>
            </select>
            <textarea name="content" cols="30" rows="10" placeholder="留言(必填)" required></textarea>
            <input type="submit" />
        </form>
    </div>
</body>
</html>


(二):valid和invalid美化表单验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title></title>
    <style type="text/css">
        *{margin: 0;padding: 0;}
        .container{
            width: 600px;
            margin: 30px auto;
        }
        form>.form-group{
            position: relative;
        }
        input{
            width: 240px;
            height: 20px;
            line-height: 20px;
            padding: .5em 1em;
            outline: 0;
            text-indent: 30px;
            border-radius: 6px;
        }
        input+label{
            position: absolute;
            top: 6px;
            left: 10px;
        }
        input,input+label{
            transition: all .4s;
        }
        input:valid{
            border: 1px solid #C0FF3E;
        }
        input:invalid{
            border: 1px solid #aa0088;
        }
        input:hover,input:focus,input:valid{
            text-indent: 0px;
        }
        input:hover+label,input:focus+label,input:valid+label{
            transform: translateX(-150%);
        }

        input:valid~span.tip::after{
            content: attr(data-right-tip);
        }
        input:invalid~span.tip::after{
            content: attr(data-error-tip);
        }

    </style>
</head>
<body>
    <div class="container">
        <form action="#">
            <div class="form-group">        
                <input type="email" id="email" name="email" required autocomplete="off" placeholder="请输入邮箱" />
                <label for="email">邮箱</label>
                <span class="tip" data-right-tip="您输入邮箱正确" data-error-tip="你输入邮箱错误"></span>
            </div>
        </form>     
    </div>
</body>
</html>

这里写图片描述
这里写图片描述


五、HTML5自带表单验证常用事件

常用的三个事件:

事件 说明
oninput 实施监听input框中的输入的值
oninvalid 当输入的值不符合验证约束触发
onchange onchange 当文本框失去焦点时,检查input里的值是否符合要求,执行函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>常用表单事件</title>
    <style>
        .container{
            width: 600px;
            margin: 40px auto;
        }
        form>div.form-group{
            margin-bottom: 30px;
        }
        input,select{
            width: 240px;
            padding:5px;
            height: 40px;
            line-height: 40px;
            box-sizing: border-box;
            border-radius: 7px;
            outline: 0;
            border: 1px solid #999;
        }
        input:valid{
            border: 1px solid #00FF00;
        }
        input:focus:invalid{
            border: 1px solid #FF0000;
        }
        input[type="submit"]{
            height: 30px;
            padding: 5px;
            line-height: 30px;
            border: 1px solid #999;
        }
    </style>
</head>
<body>
    <div class="container">
        <form action="#">
            <div class="form-group">
                <label for="username">手机</label>
                <input type="text" name="username" id="username" pattern="^1[0-9]{10}$" placeholder="请输入手机号码" required oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('请输入正确手机号码!')" />
            </div>
            <div class="form-group">
                <label for="passward">密码</label>
                <input type="password" name="password" id="password" pattern="^[a-zA-Z0-9]\w{5,19}$" placeholder="请输入密码" required oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('请输入正确密码')" onchange="checkpassword()" />
            </div>
            <div class="form-group">
                <label for="repassward">确认密码</label>
                <input type="password" name="repassword" id="repassword" placeholder="请确认密码" required onchange="checkpassword()" />
            </div>
            <div class="form-group">

                <label for="select">选项</label>
                <select name="select" id="select">
                    <option value="" checked>-- 无 --</option>
                    <option value="0">必填选项1</option>
                    <option value="1">必填选项2</option>
                    <option value="2">必填选项3</option>
                    <option value="3">必填选项4</option>
                </select>
            </div>
            <div class="form-group">
                <input type="submit"/>
            </div>
        </form> 
    </div>
    <script>
        function checkpassword(){
            var passwordEle = document.getElementById('password');
            var repasswordEle = document.getElementById('repassword');          
            if(passwordEle.value!=repasswordEle.value){
                repasswordEle.setCustomValidity('两次输入密码不一致!');
            }else{
                repasswordEle.setCustomValidity('');
            }
        }
    </script>
</body>
</html>

六、HTML5自带验证默认气泡美化

使用伪类元素不靠谱。
目前的思路:

  1. 阻止浏览器默认气泡提示
  2. 创建新的统一样式的气泡提示

例子1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阻止默认气泡</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div.container{
            width: 600px;
            margin: 30px auto;
        }
        .tip{
            color: #FF0000;
        }

        form>div{
            margin: 30px 0 30px 0;
        }
        form>div>label{
            display: inline-block;
            width: 100px;
        }
        form>div>input{
            width: 240px;
        }
    </style>
</head>
<body>
    <div class="container">
        <form action="#" autocomplete="off" id="myform">
            <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" name="username" id="username" placeholder="请输入用户名" required />
                <span class="tip"></span>
            </div>
            <div class="form-group">
                <label for="password">密码:</label>
                <input type="password" name="password" id="password" placeholder="请输入密码" required />
                <span class="tip"></span>
            </div>
            <div class="form-group">
                <label for="email">邮箱:</label>
                <input type="email" name="email" id="email" placeholder="请输入邮箱" required />
                <span class="tip"></span>
            </div>
            <div class="form-group">
                <input type="submit" id="submit" />
            </div>
        </form>     
    </div>
    <script>
        var formEle = document.getElementById('myform');
        initInvalidity(formEle);

        function initInvalidity(form){

            form.addEventListener('invalid',function(event){
                event.preventDefault();
            },true);    //阻止浏览器的默认气泡,在捕获阶段

            form.addEventListener('submit',function(event){
                if(!this.checkValidity()){
                    event.preventDefault();

                }
            },true);

            var submitBtn = document.getElementById('submit');
            submit.addEventListener('click',function(event){
                var inValidEle = form.querySelectorAll(":invalid");

                for(var i=0,len=inValidEle.length; i<len; ++i){
                    inValidEle[i].parentNode.getElementsByClassName('tip')[0].innerHTML = '';
                }

                for(var i=0,len=inValidEle.length; i<len; ++i){
                    inValidEle[i].parentNode.getElementsByClassName('tip')[0].innerHTML = inValidEle[i].validationMessage;
                }

            });
        }
    </script>
</body>
</html>

美化的样式没写
这里写图片描述

例子2

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<style>
.oneline {
    line-height: 1.5;
    margin: 10px auto;
}

.oneline label {
    width: 100px;
    text-indent: 15px;
    font-size: 14px;
    font-family: "Microsoft Yahei";
    display: inline-block;
}

.oneline .sinput {
    width: 60%;
    height: 30px;
    border-radius: 6px;
    border: 1px solid #e2e2e2;
}

.oneline input[type="submit"] {
    margin-left: 20px;
    width: 80px;
    height: 30px;
    border: 0;
    background-color: #5899d0;
    color: #fff;
    font-size: 14px;
    border-radius: 6px;
}

.error-messages {
    color: red;
}
</style>

<body>
    <form id="forms">
        <div class="oneline">
            <label for="name">用户名:</label>
            <input id="name" class="sinput" name="name" type="text" required>
        </div>
        <div class="oneline">
            <label for="email">Email:</label>
            <input id="email" class="sinput" name="email" type="email" required>
        </div>
        <div class="oneline">
            <input type="submit" id="submits" value="提交">
        </div>
    </form>
    <script>
    function replaceValidationUI(form) {
        form.addEventListener("invalid", function(event) {
            event.preventDefault();
        }, true);
        form.addEventListener("submit", function(event) {
            if (!this.checkValidity()) {
                event.preventDefault();
            }
        });

        var submitBtn = document.getElementById('submits');
        submitBtn.addEventListener("click",function(){
            var invalidFields = form.querySelectorAll(':invalid'),
            errorMessages = form.querySelectorAll('.error-messages');

            for(var i=0,len=errorMessages.length; i<len; ++i){
                errorMessages[i].parentNode.removeChild(errorMessages[i]);
            } 

            for(var i=0,len=invalidFields.length; i<len; ++i){
                invalidFields[i].parentNode.insertAdjacentHTML("beforeend","<div class='error-messages'>"+invalidFields[i].validationMessage+"</div>");
            }

            if (invalidFields.length > 0) {
                invalidFields[0].focus();
                //errorMessages.style.display = "block";
            }
        });


    }
    var forms = document.getElementById("forms");
    replaceValidationUI(forms);
    </script>
</body>

</html>

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39141044/article/details/80721154
今日推荐