1. 程式人生 > >H5表單驗證2(h5自帶驗證美化)

H5表單驗證2(h5自帶驗證美化)

h5自帶驗證美化:要做出不一樣的表單驗證,我們要了解一些偽類及css選擇器。

  • :required和:optional
  • :in-range和:out-of-range
  • :valid和:invalid
  • :read-only和:read-write
//:required和:optional
<style>
        .container{
            max-width: 400px;
            margin: 20px auto;
        }
        input,select,textarea{
            width: 240px;
            margin: 10px 0;
            border: 1px solid #999;
            padding: 0.5em 1em;
        }
        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: '(選填)';
        }
/*瀏覽器預設focus的時候沒有邊框*/
        input:focus,select:focus,textarea:focus{
            outline: 0;
        }
/*focus的時候加自定義邊框*/        
        input:required:focus,textarea:required:focus{
            box-shadow: 0 0 3px 1px #aa0088;
        }


        input:optional:focus,textarea:optional:focus{
            box-shadow: 0 0 3px 1px #999;
        }

        input[type="submit"]{
            background-color: #c0a;
            border: 2px solid #a08;
            padding: 10px 0;
            color: #ffffff;
            width: 300px;
        }
        input[type="submit"]:hover{
            background-color: #a08;
        }
    </style>
</head>
<body>
<div class="container">
    <form action="#">
        <input type="name" required><label>名稱</label>
        <input type="email" required><label>郵箱</label>
        <input type="tel"><label>手機</label>
        <input type="url"><label>網址</label>
        <select name="#" id="##">
            <option value="1">非必填選項一</option>
            <option value="2">非必填選項二</option>
            <option value="3">非必填選項三</option>
            <option value="4">非必填選項四</option>
        </select>
        <textarea name="#" id="#" cols="30" rows="10" required>留言 (必填)</textarea><br/>
        <!--<button></button>-->
        <input type="submit" value="提交表單"/>
    </form>
</div>

</body>

  • 利用:valid和:invalid製作純css的表單驗證。 

 

 <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: 3px;

        }
        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>
</head>
<body>
<div class="container">
    <input type="email" id="mail" required placeholder="輸入郵箱"/>
    <span class="title">郵箱</span>
    <label for="mail"></label>
</div>
</body>
  • h5表單美化綜合案例演示:
  •     用到三個事件:
  1. oninput事件
  2. oninvalid事件
  3. onchange事件

帶*是必填項。填寫正確邊框變綠出現綠色√。填寫錯誤邊框變紅出現紅色❌。

判斷驗證密碼與確認密碼是否一致。

setCustomValidity()改變預設提示。

  <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("images/img/star.jpg") no-repeat 90% center;/*x軸偏移量90% y軸center*/
        }
        /*必填驗證通過*/
        input:required:valid,select:required:valid{
            background: url("images/img/right.png") no-repeat 90% center;
            box-shadow: 0 0 5px green;
            border-color: green;
        }
        /*不通過驗證.一開始肯定是錯誤的*/
        input:focus:invalid,select:focus:invalid{
            background: url("images/img/error.png") no-repeat 90% center;
            box-shadow: 0 0 5px red;
            border-color: red;
            outline: red solid 1px;
        }
    </style>
</head>
<body>
<form action="" class="myform">
    <div class="onelist">
        <label for="UserName">手機號</label>
        <input type="text" name="UserName" id="UserName" placeholder="請輸入手機號碼" pattern="^[0-9]{10}$" required oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('請輸入正確的手機號')"/>
    </div>
    <div class="onelist">
        <label for="Password">密碼</label>
        <input type="password" name="Password" id="Password" placeholder="6~20位" pattern="^[a-zA-Z0-9]\w{5-19}$" required oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('請輸入正確的密碼')" onchange="checkpassword()"/>
    </div>
    <div class="onelist">
        <label for="Repassword">確認密碼</label>
        <input type="password" name="Repassword" id="Repassword" placeholder="確認密碼" required onchange="checkpassword()"/>
    </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');
        var pass2=document.getElementById('Repassword');
        if(pass1.value!=pass2.value){
            pass2.setCustomValidity("兩次密碼輸入不一致");
        }else{
            pass2.setCustomValidity("");
        }
    }
</script>
</body>

練習:

  1.     不寫樣式,只是選擇input符合驗證時的label,input符合驗證時valid,input不符合驗證時invalid
  2.      選擇label,label和Input是同一父級元素,因此用~選擇器
  3.      input獲得焦點是focus
  4.     span是input相鄰兄弟元素,因此用加號選擇器。
  • 修改預設氣泡樣式:

預設氣泡在各個瀏覽器中也不一樣。

在谷歌29之前的版本我們可以通過如下偽元素修改,::webkit-validation-bubble.但是之後廢棄了。

方法:

  • 用外掛
  • 用自己的方式
  •           1.阻止預設氣泡
  •           2.建立新的氣泡
<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; margin-left: 100px}
    </style>
</head>
<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" 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();
            }
        },true)

        //提交之後,做一個點選的提交事件
        var submitBtn=document.getElementById("thesubmit");
        submitBtn.addEventListener("click",function(event){
            var inValidityField=form.querySelectorAll(":invalid");//不符合驗證資訊的
            var errorMessage=form.querySelectorAll(".error-messages");//清掉所有錯誤資訊
            var parent;

            //迴圈每一個錯誤資訊
            for(var i=0;i<errorMessage.length;i++){
                errorMessage[i].parentNode.removeChild(errorMessage[i]);
            }

            //新增新的錯誤資訊  錯誤資訊:validationMessage
            for(var i=0;i<inValidityField.length;i++){
                parent=inValidityField[i].parentNode;
                parent.insertAdjacentHTML("beforeend","<div class='error-messages'>"+inValidityField[i].validationMessage+"");
            }

            if(inValidityField.length>0){
                inValidityField[0].focus();
            }
        })

    }
    var form=document.getElementById('forms');
    replaceInvalidityUi(form);
</script>
</body>

用beforebegin可以將表單錯誤提示資訊插入到元素本身之前。