H5 form validation summary

A, form validation type

Forms validation is usually divided into two kinds:

1.form form submission background verification; 2.ajax without refreshing the page verification

Form validation method is divided into: browser authentication, server authentication, the browser and server-side two-factor authentication technology validation and ajax

Two, H5 form the basic characteristics of introduction

required: Set form element required; pattern: form elements using regular;

novalidate: used in the form tag, said in the form set required, do not verify that the form is submitted (not mandatory to fill)

formnovalidate: use the button on the input form, when the form is submitted not mandatory verification (required)

autocomplete: automatically prompts; ban is automatically prompt autocomplete = "off"

 for: id corresponding to a value corresponding to the input

    <label for="">工号</label>
    <input type="text" name="user" placeholder="请输入工号" pattern="^d{5}">

Three, H5 form validation API

Mainly has the following API:

1.validity properties : the corresponding property sheet set is set to set and meet return true

用户名:<input type="text" name="" id="username">
<script type="text/javascript">
    var username=document.getElementById('username');
    console.log(username.validity);
</script>
打印validity属性如下

valueMissing: verification required, the input tag as required, but not fill in the form of the values true

      Usage: in the input form required attribute to true

<input type="text" name="myText" required>

typeMismatch: verify compliance with a certain type, such as a form set type = "email", if the value is not entered in the form of email type, or false

      Usage: type attribute specifies a form control

<input type="email" name="myEmail"> 

patternMismatch: Verify that the value entered is in line with the regular expression, does not meet the return false

      Usage: Set pattern characteristic of the control on the form, and given the appropriate matching rules

<input type="text" name="IdCard" pattern="[0-9]{16}">

tooLong: Verify the form of characters maxLength Maximum length

      Usage: Set maxLength properties on the form controls

<input type="text" name="limit" maxLength="100">

tooShort: verification form characters minimum length minLength

      Usage: Set minLength properties on the form controls

 

<input type="text" name="limit" minLength="30">

 

rangeUnderflow: Verify the maximum input min

      Usage: Set min to form control characteristics, and gives the minimum allowed

<input type="range" name="age" min="18">

rangeOverflow: Verify the minimum input max

      Usage: Set max form control characteristics, and gives the minimum allowed

<input type="range" name="age" min="35">

stepMismatch: Input does not conform to step calculate the characteristics of the rules

      Usage: set step properties to form controls, specify the value of the increment

<input type="range" name="Level" min="0" max="100" step="5">

Form elements for the fill value may need to set min, max, and step characteristic, which limits the input value must be a multiple of the minimum value and the step characteristic. As the range of from 2 to 6, step characteristic value 2, because a legitimate value is even within the range, the other values ​​are not validated. If the input value does not meet the requirements, stepMismatch property returns true, otherwise false.

 <Input type = "number" value = "0.02" id = "numbers" step = "3" oninput = "checkLength (this, 5)"> <- when stepMismatch corresponding to STEP, where 3 is provided, click down arrow,! every time new 3 ->

badInput: user provides input elements of a browser does not recognize

customError: custom validation error message setCustomValidity ()

Custom validation message typical use case is whether the validation control values ​​coincide. For example, two password and password confirmation value does not match the input frame. As long as the custom validation message, the control will be in an inactive state, and customError returns true. To clear the error, just call setCustomValidity on the control ( "") can be.

    <form action="">
        <input type="text" id="username" value="" required pattern="^\d{4}" placeholder="请输入代码" oninput="checkit(this)">
        <input type="submit" value="验证">
    </form>
    <script>function checkit(obj){
            console.log(obj.validity);var it=obj.validity;
            if(it.valueMissing===true){
                obj.setCustomValidity("不能为空");
            }else{
                if (it.=== patternMismatch "must be a four digit"
                    obj.setCustomValidity () {to true
        
            );
                } else {
                    obj.setCustomValidity("");
                }
            }
        }
    </script>

Three, H5 comes verify beautification

1, in the form of selectors and pseudo-classes, form validation allows us to display more beautiful

: Required and: optional; required and optional fields

: In-range and: out-of-range; within the range and not within the scope of

: Valid and: invalid; in line with form validation, form validation and do not meet the

: Read-only and: read-write; read-only and writable

<style type = "text / CSS"> 
    .container { 
        max - width: 400px; margin: Auto 20px; 
    } 
    INPUT, SELECT, TextArea {width: 240px; margin: 10px 0; border: 1px Solid # 999 ; padding:. 1em 5em;} 
    label {Color: # 999; margin- left: 10px;}
     / * optional and required different style settings * / 
    INPUT: required, TextArea: required {   / * required pattern * / 
        border - right: 3px Red Solid; 
    } 
    INPUT: optional, SELECT: optional {   / * optional style * / 
        border -right: 3px Orange Solid ; 
    } 
    INPUT: required+ label::after{
        content: "(必填)"
    }
    input:optional + label::after{
        content: "(选填)"
    }
    input:focus,select:focus,textarea:focus{outline:0;}
    input:required:focus,textarea:required:focus{  
        box-shadow: 0 0 3px 1px red;
    }
    input:optional:focus,textarea:optional:focus{  
        box-shadow: 0 0 3px 1px orange;
    }
    input[type="submit"]{
        background-color: orange;
        padding: 2px 0;
        color: #fff;
    }
    input[type="submit"]:hover{
        background-color: orange;
    }
</style>
</head>
<body>
<div class="container">
    <form action="#">
        <input type="text" required><label>名称</label>
        <input type="email" required><label>邮箱</label>
        <input type="tel"><label>手机</label>
        <input type="url"><label>网址</label>
        <select name="#">
            <Option value = ". 3"> Option 3 </ option>
            <Option value = "2"> Option 2 </ option>
            <option value = "1"> Option 1 </ option>
            <option value="4">选项四</option>
        </select>
        <textarea name="#" cols="30" rows="10" placeholder="留言(必填)" required></textarea>
        <input type="submit" value="提交表单">
    </form>
</div>
</body>

 

 Remove the default style webkit core form, with -webkit-appearance: none

Will clear the search icon input box back into the style you want;

INPUT [type = "Search"] :: - Cancel-WebKit-Search-Button { // may not be compatible with the phone side 
    -webkit- Appearance: none; 
    height: 15px; 
    width: 15px; 
    background - Color: Red; 
}

Click on the arrow to remove the upper and lower number of types of input box

input [type = number] :: - webkit-outer-spin-button {/ * number and down arrows input type tag removed * /
-webkit-Appearance: none;
margin: 0;
}

 2, when the value of our input does not satisfy the constraints ,, browser will pop up an error message, then each browser shows the error message are not the same, then we need to unify their style

The principle is to prevent the default error message bubble, then create a new bubble

<style>
    .container{
        margin:10px;
    }
    .oneline{
        height: 40px;
    }
    .oneline label{
        width: 60px;display: inline-block;
    }
    .oneline .sinput{
        width:220px;
    }
    input[type="submit"]{width: 80px;height: 30px;line-height:30px;margin-left:80px; }
    .error-message{color: red;font-size: 12px;text-indent: 65px;}
</style>
</head>
<body>
<div class="container">
    <form action="#" id="forms">
        <div class="oneline">
            <label for="name">用户名:</label>
            <input id="name" name="name" class="sinput" required="">
        </div>
        <div class="oneline">
            <label for="email">邮箱:</label>
            <input id="email" name="email" class="sinput" type="email" required>
        </div>
        <div class="oneline">
            <input type="submit" value="提交" id="thesubmit">
        </div>
    </form>
</div>
    <script>(Event) {  function
            form.addEventListener ( "invalid",ideas: 1. First stop it bubbling, 2 to remove the error message, add 3 error message..//replaceInvalidityUi (form) {
            function
        // here directly bind to form an event, do not need to go to every input binding 
                event.preventDefault (); 
            }, to true ); 
            form.addEventListener ( "the Submit", function (Event) {
                 IF (! The this .checkValidity ()) { 
                    the event.preventDefault (); 
                } 
            }, to true ); 

            // the insertAdjacentHTML () method of the specified text parsing element element, and the result is inserted into the specified position of the node in the DOM tree. It does not re-render the element it is using, so it does not break existing elements within the element. This avoids the additional sequence of steps to make it faster than using innerHTML operation. element.insertAdjacentHTML (position, text); 
            // position 
// a DOMString, showing the insertion position of the element with respect to the content, and must be one of the following string: 
//'beforebegin': the front of the element itself. 
// 'afterBegin': element inserted inside before the first child node. 
// 'beforeEnd': after the last child node into the interior of the element. 
// 'afterEnd': the back of the element itself. 
// text 
// to HTML or XML is parsed into elements, and inserted into DOMString DOM tree 
            var submitBtn = document.getElementById ( "thesubmit" ); 
            submitBtn.addEventListener ( "the Click", function (Event) {
                 var inValidityField form.querySelectorAll = ( ": invalid" ), 
                errorMessage = form.querySelectorAll (. "error-Message" ), 
                parent; 
//Here directly through the error information before error-message class name to find and delete it, since the class name is the original error message error-message 
                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();
                }
            })
        }
        form=document.getElementById("forms");
        replaceInvalidityUi(form);
    </script>
</body>

 

 

Guess you like

Origin www.cnblogs.com/lita07/p/12502794.html