JavaScript form validation

Preface: the form verification we talked about this time uses the contents of the previous articles, which is more difficult than the previous ones. I will explain it in detail in the form of comments in the code.

catalogue

I Simple form validation

Verification method 1:

Verification method 2:

II Regular verification

I Regular rules

Content

Times

II Regular precautions

III Secondary linkage

I Simple form validation

 

Verification method 1:

<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        span {
            color: red;
            font-weight: bold;//Font thickness
        }
    </style>
</head>
<body>
<form action="" id="myForm">
     //Onkey, onkeyup when the key is clicked
    <p>name: <input type="text" id="userName" onkeyup="checkName(this)"><span id="l1"></span></p>
    <p>password: <input type="text" id="userPwd" onkeyup="checkPwd(this)"><span id="l2"></span></p>
    <p>mailbox: <input type="text" id="userEmail" onkeyup="checkEmail(this)"><span id="l3"></span></p>
    <p>
        <button>Sign in</button>
    </p>
</form>
<script>


    //Used to check the name for compliance
    function checkName() {
        /*Define the length of a value to get the value of the name input box*/
        var length = userName.value.length
        if (length > 0) {//There's something in it
            //The size of the name should be between 3-6 (define the length of the value)
            if (length >= 3 && length <= 6) {
                l1.textContent = "😊"
                return true
            }
            //Out of range
            l1.textContent = "Length must be within 3-6 between"
            //You must return a value, otherwise it will be overwritten. Return has the function of interruption
            return false
        }
        //There's nothing in it
        l1.textContent = "Length must be greater than 0"
        return false
    }

    //Used to check whether the password is compliant
    function checkPwd() {
        var length = userPwd.value.length
        if (length > 0) {//There's something in it
            //The size of the name should be between 3-6
            if (length >= 3 && length <= 6) {
                l2.textContent = "😊"
                return true
            }
            //Out of range
            l2.textContent = "Length must be within 3-6 between"
            return false
        }
        //There's nothing in it
        l2.textContent = "Length must be greater than 0"
        return false
    }

    //Used to check whether the mailbox is compliant
    function checkEmail() {
        var length = userEmail.value.length
        if (length > 0) {//There's something in it
            //The size of the name should be between 3-6
            if (length >= 3 && length <= 6) {
                l3.textContent = "😊"
                return true
            }
            //Out of range
            l3.textContent = "Length must be within 3-6 between"
            return false
        }
        //There's nothing in it
        l3.textContent = "Length must be greater than 0"
        return false
    }

    //Add submit event (with return value)
    myForm.onsubmit = () => {
        //To block the submission of the form, you need to return false
        //There are two ways
        //First: return checkname() & & checkpwd() & & checkemail()
        //Second:
        var f1 = checkName()
        var f2 = checkPwd()
        var f3 = checkEmail()
        return f1 && f2 && f3
    }
</script>
</body>
</html>

Verification method 2:

This is the optimization of the above code

<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        span {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
<form action="" id="myForm">
    <p>name: <input type="text" id="userName" onkeyup="checkLabel(this)"><span><i class="error"></i></span></p>
    <p>password: <input type="text" id="userPwd" onkeyup="checkLabel(this)"><span><i class="error"></i></span></p>
    <p>mailbox: <input type="text" id="userEmail" onkeyup="checkLabel(this)"><span><i class="error"></i></span></p>
    <p>
        <button>Sign in</button>
    </p>
</form>
<script>

    //Used to check compliance
    function checkLabel(obj) {
        var length = obj.value.length
        //The input tag and span tag are both in the p tag. They are brothers and can get the next adjacent element
        // var label=obj.nextElementSibling
        //Add an i tag to the span tag to get the previous element adjacent to the parent element of the i tag
        var label = obj.parentElement.getElementsByClassName("error")[0]
        if (length > 0) {//There's something in it
            //The size of the name should be between 3-6
            if (length >= 3 && length <= 6) {
                label.textContent = "😊"
                return true
            }
            //Out of range
            label.textContent = "Length must be within 3-6 between"
            return false
        }
        //There's nothing in it
        label.textContent = "Length must be greater than 0"
        return false
    }

   
    //Add submit event (with return value)
    myForm.onsubmit = () => {
        //To block the submission of the form, you need to return false
        // return checkName()&&checkPwd()&&checkEmail()
        var f1 = checkLabel(userName)
        var f2 = checkLabel(userEmail)
        var f3 = checkLabel(userPwd)
        return f1 && f2 && f3
    }
</script>
</body>
</html>

Operation results:

 

 

 

II Regular verification

I believe all of you should know regular expressions, but I still want to talk about regular expressions. Regular expressions are also called regular expressions. They are a logical formula for string operation, that is, using some specific characters defined in advance and the combination of these specific characters to form a "regular string", This "rule string" is used to express a kind of filtering logic for strings.
What can regular expressions be used for?
Given a regular expression and another string, we can achieve the following objectives:
    1. Check whether the given string conforms to the filtering logic of regular expression, that is, whether it can match;
    2. You can extract or replace specific parts from a string by matching regular expressions.

I Regular rules

Content

\dNumber [0-9]
\DNon numeric ^ [0-9]
\wNumber + English + underline [0-9a-zA-Z_]
\WNon numeric + English + underline ^ [0-9a-zA-Z_]
.Any character

Times

0 ~ 1 times
+At least once
*0 ~ any time
\d{5}Five numbers (any number)
\d{5,10}At least five times and at most 10 times (fill in any number)

II Regular precautions

Must start with / ^
Must end with $/
Don't write \ as\
Define regular objects (for example): var , rex=/^\d{5}$/

Use regular objects (for example): Rex test('123')

Next, let's write a simple verification using regular

<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        span {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
<form action="" id="myForm">
    <p>name: <input type="text" id="userName" onkeyup="checkLabel(this,/^[a-zA-Z]{3,6}$/,'The length of the name is 3-6')"><span><i class="error"></i></span></p>
    <p>password: <input type="text" id="userPwd" onkeyup="checkLabel(this,/^\w{6,10}$/,'The length of the password is 6-10')"><span><i class="error"></i></span></p>
    <p>mailbox: <input type="text" id="userEmail" onkeyup="checkLabel(this,/^\w+[.]\w+@\w+[.]\w+$/,'Mailbox must contain@')"><span><i class="error"></i></span></p>
    <p>
        <button>Sign in</button>
    </p>
</form>
<script>

    //Used to check compliance
    //In parentheses are the values passed in
    function checkLabel(obj,rex,tip) {
        var length = obj.value.length
        var label = obj.parentElement.getElementsByClassName("error")[0]
        if (length > 0) {//There's something in it
            //Content between regular matches
            if (rex.test(obj.value)) {
                label.textContent = "😊"
                return true
            }
            //Out of range
            label.textContent = tip
            return false
        }
        //There's nothing in it
        label.textContent = "Length must be greater than 0"
        return false
    }

    //Add submit event (with return value)
    myForm.onsubmit = () => {
        //To block the submission of the form, you need to return false
        // return checkName()&&checkPwd()&&checkEmail()
        var f1 = checkLabel(userName)
        var f2 = checkLabel(userEmail)
        var f3 = checkLabel(userPwd)
        return f1 && f2 && f3
    }
</script>
</body>
</html>

III Secondary linkage

Does the word secondary linkage sound very advanced, but it is actually very common in our life. You can know what it is at a glance o(T ヘ To)

<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
//select drop-down box, provinces, onchange change event
<select id="province" onchange="myChange()"></select>
<select id="cities"></select>

<script>

    //Characteristics of JS array
    //Unlimited types
    //Unlimited length
    //Arrays can be strings
    var provinces=[]
    //city
    provinces["Hunan Province"]=["Changsha","Huaihua","Yueyang"]
    provinces["Guangxi Province"]=["Guilin","Wuzhou","guest"]
    provinces["Zhejiang Province"]=["Hangzhou","Ningbo","Zhoushan"]

    //How did the province come from
    //  for of is equivalent to a foreach traversal element
    //  for in traversal subscript
    for(let i in provinces){
        //Add an option to the drop-down box of the province
        //appendChild append child node
        //<option value="i">i</option>
        //The first i is the value and the second i is the displayed value
        province.appendChild(new Option(i,i))
    }

    //Put value in the city
    function setCity(name) {
        for(let i of provinces[name]){
            cities.appendChild(new Option(i,i))
        }
    }

    setCity(province.value)

    function myChange() {
        //Clear the original option
        cities.innerHTML=""
        //You can get value in the input box and drop-down box
        setCity(province.value)
    }
</script>
</body>
</html>

Operation results:

 

Well, this article is over everywhere. I look forward to seeing you in our next article ( ̄▽  ̄)“

Keywords: Javascript ECMAScript

Added by gameshints on Sun, 06 Mar 2022 17:13:17 +0200