Html5 表单验证

2019-08-02  本文已影响0人  3132

基本表单验证特性介绍

email、URL、number、range、date(date, month, week, time, datetime, datetime-local )、search、color、tel等
<from action="" method="post" enctype="multipart/form-data" novalidate="novalidate" ></from>

<input type="submit" formnovalidate="formnovalidate">

约束验证API

html
<form name="test" action="" method="post">
    <input type="text" required pattern ="^\d{4}$" oninput="checkit(this)" placeholder="请输入">
    <input type="submit" value="验证">
</from>

script
<script>
function checkit(obj){
    var it = obj.validity;
    if(true === it.valueMissing){
        obj.setCustomValidity("不能为空!");
    }else{
        if(true === it.patternMismatch){
            obj.setCustomValidity("必须是4个数字");
        }
    }
</script>

Html 5 自带验证美化

<!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-message{color:red;font-size:12px;text-indent: 108px;}
</style>
<body>
<form>
    <div class="oneline">
        <label for="name">用户名:</label>
        <input id="name" name="name" class="sinput"  required>
    </div>
    <div class="oneline">
        <label for="email">Email:</label>
        <input id="email" name="email" class="sinput"  type="email" required>
    </div>
    <div class="oneline">
        <input type="submit" value="提交">
    </div>
</form>
<script>
        function replaceValidationUI( form ) {
        // 为from表单增加"验证失败"监听事件,并且阻止默认气泡
        form.addEventListener( "invalid", function( event ) {
            event.preventDefault();
        }, true );
            //监听提交事件,验证不通过时,阻止默认提交事件
        form.addEventListener( "submit", function( event ) {
            if ( !this.checkValidity() ) {
                event.preventDefault();
            }
        });

        var submitButton = form.querySelector( "button:not([type=button]), input[type=submit]" );

        submitButton.addEventListener( "click", function( event ) {
            //  获取所有不符合的验证信息,获取所有错误信息(为了清除错误信息),定义变量插入
            var invalidFields = form.querySelectorAll( ":invalid" ),
                errorMessages = form.querySelectorAll( ".error-message" ),
                parent;

          //  删除错误信息的父类
            for ( var i = 0; i < errorMessages.length; i++ ) {
                errorMessages[ i ].parentNode.removeChild( errorMessages[ i ] );
            }
             //  获取没有通过验证的错误信息,为错误信息的父类添加我们自己的样式
            for ( var i = 0; i < invalidFields.length; i++ ) {
                parent = invalidFields[ i ].parentNode;

             //  insertAdjacentHTML() 知识点
                parent.insertAdjacentHTML( "beforeend", "<div class='error-message'>" + 
                    invalidFields[ i ].validationMessage +
                    "</div>" );
            }
            //  如果有错误信息,第一个定位焦点
            if ( invalidFields.length > 0 ) {
                invalidFields[ 0 ].focus();
            }
        });
    }
        //  通过css选择器获取所有form表单
    var forms = document.querySelectorAll( "form" );
    for ( var i = 0; i < forms.length; i++ ) {
        replaceValidationUI( forms[ i ] );
    }
    
</script>
上一篇 下一篇

猜你喜欢

热点阅读