【前端基础】9.html5表单验证美化

视频

一,html5基本表单特性

<!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>
</head>
<body>  
        <!-- autocomplete="off"不记住密码,"on"记住密码 -->
        <form action="" method="post" enctype="multipart/form-data" autocomplete="off"> 
        <!-- novalidate自动提交表单,不验证,不会出现提示必填 -->
        <!-- <form action="" method="post" enctype="multipart/form-data" novalidate></form> -->
        
        <!-- 设置type="file"必须加enctype="multipart/form-data" 因为form-data要传到后台去-->
        <input type="file">

        <label for="">用户名</label>
        <!-- required:必填 -->
        <input type="text" name="user" placeholder="请输入用户名" required />
        <!-- autofocus="autofuces"或直接autofocus:自动聚焦 -->
        <!-- <input type="text" name="user" placeholder="请输入用户名" required  autofocus/> -->
        
        <label for="">工号</label>
        <!-- pattern规定格式:\d{5} 五位数字,[imooc] 任选一个-->
        <input type="text" name="gonghao" placeholder="请输入工号" pattern="^\d{5}[imooc]$">

        <!-- 和第一行的novalidate相区别,也是不会提示,会提交到后台 -->
        <!-- <input type="submit" name="" formnovalidate=""> -->

        <!-- 下拉可选列表 -->
        <input type="text" list="tips">
        <datalist id="tips">
            <option value="erwerew1r"></option>
            <option value="erwerew2r"></option>
            <option value="erwerew3r"></option>
            <option value="erwerew4r"></option>
        </datalist>

        <label for="man"></label>
        
        <!-- input[type="radio"][name="sex"] -->
        <!-- 在radio 中比较明显,点字就可以选上-->
        <input type="radio" name="sex" id="man"  required>
        <label for="woman"></label>
        <input type="radio" name="sex" id="woman" required>

        <input type="submit">
    </form>
</body>
</html>

二,html5表单约束验证API


html5的约束验证API主要有如下几个:

1.willValidate. 元素约束有没有被符合,如果没有,则返回false
2.validity. validate 元素的对象,表示元素所属的验证状态,验证是否成功
3.validationMessage.用于描述与元素相关约束的失败信息
4.checkValidity() 方法. 看元素是否满足任意约束,如果没有满足任何一个满足,返回false.
5.setCustomValidity() 方法。设置自定义验证信息。


图片

<!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>
</head>
<style>
    /*
     伪元素美化,手机端safari不支持,用绝对定位 
     去掉框末尾的“ × ”。
    */
    input[type="search"]::-webkit-search-cancel-button{
        -webkit-appearance: none;
        height: 15px;
        width: 15px;
        background-color: blueviolet;
    }

    /* 去掉上下箭头 */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button{
        -webkit-appearance: none;
        margin:0;
    }
</style>
<body>
  
    <form action="">
        <!-- 加了required,valueMissing变成true,如果在加上value="abc",就又变成false -->
        <!-- <input type="text" id="username" value="abc" required> -->

        <!--maxlength和minlength对应toolong和tooshort,toolong和tooshoort恒对应false,所有是没有是没用的  -->
        <!-- <input type="text" id="username"  maxlength="5" minlength="1"> -->
        <input type="number" id="numbers" oninput="checklength(this,5)">

        <!-- step="3"和stepMismatch匹配,每次加减3,如果想保留两位就step="0.01"-->
        <!-- <input type="number" id="numbers" step="3" οninput="checklength(this,5)"> -->
        

        <!--pattern 对应 patternMismatch,加了value="abcdefg"变成true,因为不通过 -->
        <input type="text" id="username" value="abcdefg" pattern="^\d{5}"> 

        <!-- 和typeMismatch对应,加了value="abcdefg"变成true,因为不通过-->
        <!-- <input type="url" id="url" value="abcdefg" > -->
         <input type="email" id="email" value="abcdefg" > 

        <input type="search" id="search" value="">

        <!-- max和true对应rangeOverflow和rangeUnderflow,value值超出变成true-->
        <!-- <input type="number" id="numbers" max="5" min="3" > -->

        <input type="submit">
    </form>
    

</body>

<script>
    //一般不直接用username
    //console.log(document.getElementById("username")===username);
    console.log(username.validity);
    
    console.log(email.validity);

    console.log(numbers.validity);

    //定长输入
    function checklength(obj,length){
        if(obj.value>length){
            obj.value=obj.value.substr(0,length);
        }
    }


    // checkValidaity的使用
    if(email.checkValidity()){
        alert("是一个邮箱")
    }else{
        alert("不是一个邮箱")
    }
    if(username.checkValidity()){
        alert("用户名符合")
    }else{
        alert("用户名不符合")
    }

</script>
</html>

三,html5约束验证API之setCustomValidity()

setCustomValidity()
设置自定义验证信息,用于即将实施与验证的约束来覆盖预定义的信息

<!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>form test</title>

    <style>
        input[type="text"]{border:1px solid #ccc;width:150px;height: 30px;border-radius: 5px;}
        input[type="submit"]{background-color:#eee ;border: 1px solid #ddd;width: 60px;height: 33px;border-radius: 5px;}
    </style>

</head>
<body>
    
    <form action="" method="" name="text">
        <input type="text" required pattern="^\d{4}$" oninput="checkit(this)" placeholder="请输入代码">
        <input type="submit" value="验证">
    </form>
    
    <script type="text/javascript">
        function checkit(obj){
            console.log(obj.validity);
            var it=obj.validity;
            if(true===it.valueMissing){
                obj.setCustomValidity("不能为空!");
            }else{
                if(true===it.patternMismatch){
                    obj.setCustomValidity("必须是4个数字!");
                }else{
                    obj.setCustomValidity("");
                }

            }
        }
    </script>
</body>
</html>

效果:
效果9

四,html5自带美化

一些伪类和选择器
1,:required和:optional 必填的和选填的 。
2,:in-range和:out-of-range 在范围之内和不在范围之内,通常和最大,最小值相对应。
3,:valid和:invalid 符合要求的和不符合要求的。
4,:read-only和:read-write。

  “+” 选择器:
  h1+p{margin-top:50px;}//h1后面的第一个p元素会有50px的间距
  “~” 选择器
  p~ul    //所有相同的父元素中位于p元素之后的所有ul元素
  {
      background:#ff000;
  }

required和optional美化表单

<!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>
        
        .container{max-width: 400px;margin: 20px auto;}
        input,select,textarea{width: 240px;margin: 10px 0;border: 1px solid #999;padding: .5em 1en;}
        label{color: #999;margin-left:10px;}
        input:required,textarea:required{
            border-right: 3px solid #aa0088;
        }
        input:optional,select:optional{
            border-right: 3px solid #999;
        }
        input:required +label::after{
            content: "(必填)";
        }
        input:optional +label::after{
            content: "(选填)";
        }
        input:focus,select:focus,textarea:focus{outline: 0}
        input:required:focus,select:required:focus,textarea:required:focus{
            box-shadow: 0 0 3px 1px #aa0088;
        }
        input:optional:focus,select:optional:focus,textarea:optional:focus{
            box-shadow: 0 0 3px 1px #999;
        }
        input[type="submit"]{
            background-color: #cc00aa;
            border: 2px solid #aa0088;
            padding: 10px 0;
            color: #fff;
        }
        input[type="submit"]:hover{
            background-color: #aa0088;
        }

     </style>

</head>
<body>
    
    <div class="container">
        <form action="#">
            <input class="name" required><label >名称</label>
            <input class="email" required><label >邮箱</label>
            <input class="tel"><label >手机</label>
            <input class="url"><label >网址</label>
            <select name="#" >
                <option value="1">非必填选项一</option>
                <option value="2">非必填选项二</option>
                <option value="3">非必填选项三</option>
                <option value="4">非必填选项四</option>
            </select>
            <textarea name="#" cols="30" rows="10" placeholder="留言(必填)" required></textarea>
            <input type="submit" value="提交表单">
        </form>
    </div>
</body>
</html>

效果:
自带美化

五,html5 valid和invalid伪类美化

动态表单效果

<!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>纯css表单验证美化(invalid和valid)</title>
</head>
<style>
    .container{margin: 100px;position: relative;}
    input{border:1px solid #999;outline: 0;width: 140px;height: 30px;line-height: 30px;
        text-indent: 36px;transition: all .3s;border-radius: 4px;}
    span.title{position: absolute;line-height: 30px;height: 30px;left:2px;top: 2px;
        transition:all .3s;}

     input:focus,input:hover{
        text-indent: 2px;
     }   
     input:focus +span.title,input:hover +span.title{
        transform: translateX(-120%);
     }
     input:valid ~label::after{content: "你输入邮箱正确";}
     input:invalid ~label::after{content: "你邮箱错误";}
     input:valid{border: 1px solid green;}
     input:invalid{border: 1px solid red;}
</style>
<body>
    <div class="container">
        <input type="email" id="mail" required placeholder="输入邮箱">
        <span class="title">邮箱</span>
        <label for="mail"></label>
    </div>
</body>
</html>

动态效果:
效果1效果3

六,html5表单验证美化综合

<!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>jtml5表单验证美化综合</title>

    <!-- 
        用到三个事件;
        1,onint事件
        2,oninvalid事件
        3,onchange事件

     -->
</head>

<style>
.oneList{margin:10px 0 5px 12px;}
.oneList label{width:80px;display:inline-block}
.oneList input,.oneList select{height:25px;line-height:25px;
width:220px;border-radius:3px;border:1px solid #e2e2e2;}
.oneList input[type="submit"]{width:150px;height:30px;line-height:30px;}

input:required,select:required{
    background: url(img/star.png) no-repeat 90% center;
}
input:required:valid,select:required:valid{
    background: url(img/right.png) no-repeat 90% center;
    box-shadow: 0 0 5px green;
    border-color: green;
}
input:focus:invalid,select:focus:valid{
    background: url(img/error.png) no-repeat 90% center;
    box-shadow: 0 0 5px red;
    border-color: red;
    outline: red solid 1px;
}


</style>

<body>
    <form class="myform" method="post">
        <div class="oneList">
            <label for="UserName">手机号</label>
            <input name="UserName" id="UserName" type="text" 
           placeholder="请输入手机号码" pattern="^1[0-9]{10}$" 
           oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('请输入正确手机号!')" required >
        </div>
        <div class="oneList">
            <label for="Password">密码</label>
            <input name="Password" id="Password" type="password" onchange="checkpassword()"
            oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('请输入正确密码!')" placeholder="确认密码" required>
        </div>
        <div class="oneList">
            <label for="Repassword">确认密码</label>
            <input name="Repassword" id="Repassword" type="password" onchange="checkpassword()"
            placeholder="6~20位" pattern="^[a-zA-Z0-9]\w{5,19}$" required>
        </div>
        <div class="oneList">
            <label for="Repassword">了解方式</label>
            <select name="know" required>
                <option value="">==请选择==</option>
                <option value="1">搜索引擎</option>
                <option value="2">朋友圈</option>
                <option value="3">朋友推广</option>
                <option value="4">广告投放</option>
            </select>
        </div>
        <div class="oneList">
            <input type="submit" value="提交">
        </div>
    </form>

    <script type="text/javascript">
       function checkpassword(){
           var pass1=document.getElementById("Password"),pass2=document.getElementById
           ("Repassword");
           if(pass1.value!=pass2.value){
               pass2.setCustomValidity("两次密码输入不一致");
           }else{
            pass2.setCustomValidity("");
           }
       } 
    </script>

</body>
</html>

效果:
效果4

七,默认气泡修改

在不同的内核的浏览器中,其气泡样式不同,为其,可进行默认气泡的修改。

<!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>
</head>
<style>
    .onelist{line-height: 1.5;margin: 10px auto;}
    .onelist label{width: 100px;text-indent: 15px;font-size:14px;
        font-family: "Microsoft Yahei";display: inline-block;}
    .onelist .sinput{width: 60%;height: 30px;border-radius: 6px;
        border:1px solid #e2e2e2}
    .onelist input[type="submit"]{margin-left: 20px;width:80px;height: 30px;
        border: 0;background-color: #5899d0;color: #fff;font-size: 14px;
        border-radius:6px;}
    .error-message{color: red;font-size: 12px;text-indent:108px}
</style>
<body>
    <form id="forms">
        <div class="onelist">
            <label for="name">用户名:</label>
            <input id="name" name="name" class="sinput" required>
        </div>
        <div class="onelist">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" class="sinput" required>
        </div>
        <div class="onelist">
            <input type="submit" value="提交" id="thesubmit">
        </div>  
    </form>
    <script>
      function replaceInvalidityUi(form){

            form.addEventListener("invalid",function(event){
                event.preventDefault()
            },true)
           
            form.addEventListener("submit",function(event){
                if(!this.checkValidity){
                    event.preventDefault();
                }
            })
            var submitBtn=document.getElementById("thesubmit");
            submitBtn.addEventListener("click",function(event){

                var inValidityField=form.querySelectorAll(":invalid"),
                errorMessage=form.querySelectorAll(".error-message"),
                parent;
    
               for(var i=0;i<errorMessage.length;i++){
                   errorMessage[i].parentNode.removeChild(errorMessage[i]);
               }
                for(var i=0;i<inValidityField.length;i++){
                    parent=inValidityField[i].parentNode;
                    parent.insertAdjacentHTML("beforeend","<div class='error-message'>"+inValidityField[i].validationMessage+"</div>");
                }
               if(inValidityField.length>0){
                   inValidityField[0].focus();
               }
    
            })
        }
    
      var form=document.getElementById("forms");
      replaceInvalidityUi(form);
    </script>
</body>
</html>

效果8

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值