JavaScript validates forms using form elements

Chapter 1: Validating forms using JavaScript

The main role of JavaScript: validating forms

1 Simplest form validation - Prohibit blank mandatory items

1.1 The simplest HTML structure

Registration is the most basic part of a website. It is the interaction basis of a system.

Example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Simple list html structure</title>
    </head>
    <body>
        <form method="post" action="">
            //Account: <input type="text" name="/><br/><br/><br/>
            //Password: <input type="password" name="/><br/><br/>
            //Confirm: <input type="password" name="/><br/><br/><br/>
            <input type="submit"  value="register" />
        </form>
    </body>
</html>

1.2 Binding Verification Function

Because the user finally clicks the "Registration" button, we add an onclick event attribute to the "Registration" button, referring to eg.regCheck().

Example:

Registration events

<!DOCTYPE html>
<html>
    <!--Binding Verification Function, Registering Events-->
    <head>
        <meta charset="utf-8">
        <title>Simple list html structure</title>
    </head>
    <body>
        <form method="post" action="">
            account:<input type="text" name=""/><br/><br/>
            Password:<input type="password" name=""/><br/><br/>
            confirm:<input type="password" name=""/><br/><br/>
            <input type="submit"  
            value="register"
             onclick="return eg.regCheck();"/>        
        </form>
        <script >
            //Declare an object and use it as a namespace
            var eg =  {};
            eg.regCheck = function(){
                
            }
        </script>
    </body>
</html>

The eg.regCheck() function needs to add actions to get account information entered by the user, add an id attribute to the input tag, and JavaScript uses the specified id to get the corresponding information, and then returns the validation result true or false.

Example:

Add validation to the form

<!DOCTYPE html>
<html>
    <!--Add validation to the form-->
    <head>
        <meta charset="utf-8">
        <title>Simple list html structure</title>
    </head>
    <body>
        <form method="post" action="">
            //Account: <input type="text" name=""id="userid"/><br/><br/>
            //Password: <input type="password" name=""id="userpwd"/><br/><br/>
            //Confirm: <input type="password" name=""id="userpwd2"/><br/><br/>
            <input type="submit"  
            value="register"
            onclick="return eg.regCheck();"/>
        </form>
        <script >
            //Declare an object and use it as a namespace
            //Define a common function to get the specified id elements, reduce the amount of code and improve code reuse
            var eg =  {};
            eg.$ = function(id){
                return document.getElementById(id);
                };
                eg.regCheck = function(){
                    var uid = eg.$("userid");
                    var upwd = eg.$("userpwd");
                    var upwd2 = eg.$("userpwd2");    
                if(uid.value == ''){
                    alert('Account cannot be empty!');
                    //Returning false prevents form submission
                    return false;
                }
                if(upwd.value == ''){
                    alert('Password cannot be empty!');
                    //Returning false prevents form submission
                    return false;
                }
                if(upwd.value != upwd2.value){
                    alert('Different passwords are entered twice!');
                    //Returning false prevents form submission
                    return false;
                }
                return true;
            };
        </script>
    </body>
</html>

1.3 Another way of binding validation

Put validation in the onclick event attribute of the "Registration" button, and there is another way to call it, that is, the onsubmit event attribute of the form tag

Example:

Form form binding verification complete example

<!DOCTYPE html>
<html>
<!--
//Another way of binding validation, the complete example of form form binding validation
-->
    <head>
        <meta charset="utf-8">
        <title>Simple list html structure</title>
    </head>
    <body>
        <form method="post" action="" onsubmit="return eg.regCheck();">
            //Account: <input type="text" name=""id="userid"/><br/><br/>
            //Password: <input type="password" name=""id="userpwd"/><br/><br/>
            //Confirm: <input type="password" name=""id="userpwd2"/><br/><br/>
            <input type="submit"  
            value="register"
             />
        </form>
        <script>
            //Declare an object and use it as a namespace
            //Define a common function to get the specified id elements, reduce the amount of code and improve code reuse
            var eg =  {};
            eg.$ = function(id){
                return document.getElementById(id);
                };
            eg.regCheck = function () {
                var uid = eg.$("userid");
                var upwd = eg.$("userpwd");
                var upwd2 = eg.$("userpwd2");
                if(uid.value == ''){
                    alert('Account cannot be empty!');
                    //Returning false prevents form submission
                    return false;
                }
                if(upwd.value == ''){
                    alert('Password cannot be empty!');
                    //Returning false prevents form submission
                    return false;
                }
                if(upwd.value != upwd2.value){
                    alert('Different passwords are entered twice!');
                    //Returning false prevents form submission
                    return false;
                }
                return true;

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

2. Processing various types of form elements

2.1, input,textarea,hidden and button

Requirements: On the basis of the registration form, add the "Introduction" field, which can be empty, but not more than 60 characters. At the same time, it is necessary to count the number of user input errors. If the number of input errors exceeds 3 times, the "Registration" button will be locked, and then the "Unlock" button will be used again.

Example:

Processing various types of forms

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>Handling various types of forms</title>
    </head>
    <body>
        <form method="post" action="" onsubmit="return eg.regCheck();">
            //Account: <input type="text" name=""id="userid"/><br/><br/>
            //Password: <input type="password" name=""id="userpwd"/><br/><br/>
            //Confirm: <input type="password" name=""id="userpwd2"/><br/><br/>
            //Introduction:
                <textarea name="" rows="4" cols="18" id="about">
                </textarea><br/><br/>
            <input type="submit"
            value="register" id="regBtn"
             />
            <input type="button" value="Unlock" onclick="eg.unlock"
            style="display: none;" id="regUnlock">
        </form>
        <script>
            //Declare an object and use it as a namespace
            //Define a common function to get the specified id elements, reduce the amount of code and improve code reuse
            var eg =  {};
            eg.$ = function(id){
                return document.getElementById(id);
                };
            //Main verification methods
            eg.regCheck = function () {
                var uid = eg.$("userid");
                var upwd = eg.$("userpwd");
                var upwd2 = eg.$("userpwd2");
                //value is an element's own attribute
                if(uid.value == ''){
                    alert('Account cannot be empty!');
                    eg.err();
                    return false;
                }
                if(upwd.value == ''){
                    alert('Password cannot be empty!');
                    eg.err();
                    return false;
                }
                if(upwd.value != upwd2.value){
                    alert('Different passwords are entered twice!');
                    eg.err();
                    return false;
                }
                //New additions
                var about = eg.$("about");
                //value is an attribute of string type
                if (about.value.length>60){
                    alert("Brief introduction is too long!");
                    eg.err();
                    return false;

                }
                //Returning true will submit the form
                return true;

            };
            //Record the number of errors when an error occurs
            eg.err = function () {
                var el = eg.$("errnum");
                var old = el.value;
                //Convert the string to integer + 1 and save it
                el.value = parseInt(old)+1;
                //Used to check whether locks should be made
                eg.lock();
            };
            //Determine whether to lock through the number of times
            eg.lock = function(){
                var err = eg.$("errnum");
                if (parseInt(err.value)>2){
                    eg.$("regBtn").disabled = true;
                    //Lock-in after three errors according to business requirements
                    eg.$("regUnlock").style.display="block";
                    //Display the unlock button at the same time
                }
            };
            eg.unlock = function(){
                eg.$("regBtn").disabled = false;
                //Depending on business requirements, unlocking allows users to re-register.
                eg.$("regUnlock").style.display="none";
                //All styles of the element are mounted under the style attribute
            }
        </script>
    </body>
</html>

Now make an error statistics, which can be saved for the background system to analyze the user's error rate, and can even analyze which fields the user will make mistakes in general. Recording error information does not need to be seen by the user. You can choose that the type attribute of input is hidden element to store it.

2.2 checkbox, radio and select

Know user's gender, age, hobbies and interests

Example:

Processing various types of forms II

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>Processing various types of forms II</title>
    </head>
    <body>
        <form method="post" action="" onsubmit="return eg.regCheck();">

            //Account: <input type="text" name=""id="userid"/><br/><br/>
            //Password: <input type="password" name=""id="userpwd"/><br/><br/>
            //Confirm: <input type="password" name=""id="userpwd2"/><br/><br/>
            //Introduction:
                <textarea name="" rows="4" cols="18" id="about">
                </textarea><br/><br/>
            <input type="submit"
            value="register" id="regBtn"
             />
            <input type="button" value="Unlock" onclick="eg.unlock"
            style="display: none;" id="regUnlock">
        </form>
        <script>
            //Declare an object and use it as a namespace
            //Define a common function to get the specified id elements, reduce the amount of code and improve code reuse
            var eg =  {};
            eg.$ = function(id){
                return document.getElementById(id);
                };
            //Main verification methods
            eg.regCheck = function () {
                var uid = eg.$("userid");
                var upwd = eg.$("userpwd");
                var upwd2 = eg.$("userpwd2");
                //value is an element's own attribute
                if(uid.value == ''){
                    alert('Account cannot be empty!');
                    eg.err();
                    return false;
                }
                if(upwd.value == ''){
                    alert('Password cannot be empty!');
                    eg.err();
                    return false;
                }
                if(upwd.value != upwd2.value){
                    alert('Different passwords are entered twice!');
                    eg.err();
                    return false;
                }
                //New additions
                var about = eg.$("about");
                //value is an attribute of string type
                if (about.value.length>60){
                    alert("Brief introduction is too long!");
                    eg.err();
                    return false;

                }
                //Returning true will submit the form
                return true;

            };
            //Record the number of errors when an error occurs
            eg.err = function () {
                var el = eg.$("errnum");
                var old = el.value;
                //Convert the string to integer + 1 and save it
                el.value = parseInt(old)+1;
                //Used to check whether locks should be made
                eg.lock();
            };
            //Determine whether to lock through the number of times
            eg.lock = function(){
                var err = eg.$("errnum");
                if (parseInt(err.value)>2){
                    eg.$("regBtn").disabled = true;
                    //Lock-in after three errors according to business requirements
                    eg.$("regUnlock").style.display="block";
                    //Display the unlock button at the same time
                }
            };
            eg.unlock = function(){
                eg.$("regBtn").disabled = false;
                //Depending on business requirements, unlocking allows users to re-register.
                eg.$("regUnlock").style.display="none";
                //All styles of the element are mounted under the style attribute
            }
        </script>
    </body>
</html>

Keywords: Javascript Attribute

Added by amotaz on Mon, 19 Aug 2019 13:15:04 +0300