JavaScript (form validation)

Posted by gelwa on Mon, 07 Mar 2022 08:23:46 +0100

catalogue

preface

1, What is form validation?

2, Categories of form validation

1. Simple verification

2. Regular verification

3. Secondary linkage (drop-down box)

summary

preface

Last issue introduced how to operate css. Today, let's introduce the form verification of JS.

1, What is form validation?

Get the value of the form label and compare whether the value is empty or consistent with the standard of the value you set (such as input length, character limit, etc.).

If the comparison is wrong, prompt the user (such as pop-up window) and prevent the form from submitting. Otherwise, submit the form!

2, Categories of form validation

1. Simple verification

1. Create a form:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<form action="" method="">
			<p>name:<input type="text" /></p>
			<p>password:<input type="text" /></p>
			<p>Email:<input type="text" /></p>
            <p>
				<button type="button">Sign in</button>
			</p>
		</form>
	</body>
</html>

2. Add a submit event

1.<form action="" ο Nsubmit = "return check()" > add directly

2.myForm. Onsubmit = () = > {adding by function will have a return value
          console.log("-----")
return false / / to prevent form submission, you need to return a false
        }

3. Add conditional judgment to the submission event (name cannot be empty, etc.)

 myForm.onsubmit = () => {
         var s1=userName.value
             if(s1.length==0){
alert("please enter user name")
             }
        }

4. Change the prompt box to red warning

 1. Add span label

2. Set color

<style type="text/css">
            span {
                color: red;
                font-weight: bold;
                    }

</style>

5. Common keyboard events

1.onkeydown keyboard press

2.onkeyup # it is better to use this value when loosening the keyboard, which is more accurate

3.onkeypress once

Full code:

<!DOCTYPE html>
<html lang="xly">
<head>
    <meta charset="UTF-8">
    <title>Score</title>
    <style>
        span {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
<!--<form action="" onsubmit="return check()">-->
<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 the name for compliance
    function checkLabel(obj) {
        var length = obj.value.length
        // var label=obj.nextElementSibling
        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
    }

    //Used to check the name for compliance
    function checkName() {
        var length = userName.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) {
                l1.textContent = "😊"
                return true
            }
            //Out of range
            l1.textContent = "Length must be within 3-6 between"
            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
        // return checkName()&&checkPwd()&&checkEmail()
        var f1 = checkLabel(userName)
        var f2 = checkLabel(userEmail)
        var f3 = checkLabel(userPwd)
        return f1 && f2 && f3
    }
</script>
</body>
</html>

 

2. Regular verification

usage method;

/^Regular $/ rules must start with / ^ and end with & /

Regular validation rule formula:

\d number [0-9]

\D non numeric ^ [0-9]

\w number + English + underline [0-9a-zA-Z_]

\W non numeric + English + underline ^ [0-9a-zA-Z_]

. any character

? 0 ~ 1 times

+At least once

*0 ~ any time

\d{5} five numbers

\d{5,10} minimum five times, maximum 10 times

2. Precautions

1. Rules only need \ d, not \ \ d

2. Define regular object: var rex=/^\d{5}$/

3. Use regular object: Rex test('123') 

3. Secondary linkage (drop-down box)

When browsing major websites, have you ever encountered the situation of automatic switching between provinces and cities when filling in the address? Today, let's teach you how to make the effect of provincial and municipal linkage.

The code is as follows:

<!DOCTYPE html>
<html lang="xly">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select id="province" onchange="myChange()"></select>
<select id="cities"></select>

<script>

    //How to write an array?
    //Unlimited types
    //Unlimited length
    //Arrays can be strings
    var provinces=[]
    //city
    provinces["Japan Province"]=["Hokkaido","Bridge bean sack","Moses Moses"]
    provinces["Hunan Province"]=["Changsha","Beijing","Xiba"]
    provinces["Guangxi Province"]=["younger female cousin","Snail powder","Table Guo"]


    //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 options to the drop-down box of the province
        //<option value="i">i</option>
        province.appendChild(new Option(i,i))
    }

    //Who's 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=""
        //Input box and drop-down box
        setCity(province.value)
    }
</script>
</body>
</html>

summary

That's all for today's JS knowledge sharing. More highlights. Continue in the next issue!

Topics: Javascript