Small example of JS form validation (HTML+CSS+JS) [detailed tutorial]

foreword

Hello everyone, share a HTML+CSS+JS form validation, including the simple layout of the page, style rendering, and basic JS validation methods. Hope you like it! Ha ha


1. Rendering

insert image description here
insert image description here
insert image description here

2. Introduction

Icon library using Element-UI

<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

CSS style creates a css file reference separately, or it can be written in the HTML page style tag

Address: Component | Element , you can also use other component libraries according to your preferences.

3. Code

(1)HTML

Add the code in the body tag

<div class="container">
        <div class="header">
            <h2>表单验证</h2>
        </div>
        <form class="form" id="form">
            <div class="form_control" id="form_control">
                <label for="">用户名</label>
                <input type="text" placeholder="请输入用户名" id="username">
                <i class="el-icon-success"></i>
                <i class="el-icon-warning"></i>
                <small>Error Message</small>
            </div>
            <div class="form_control" id="form_control">
                <label for="">邮箱</label>
                <input type="text" placeholder="请输入邮箱" id="email">
                <i class="el-icon-success"></i>
                <i class="el-icon-warning"></i>
                <small>Error Message</small>
            </div>
            <div class="form_control" id="form_control">
                <label for="">密码</label>
                <input type="password" placeholder="请输入密码" id="password">
                <i class="el-icon-success"></i>
                <i class="el-icon-warning"></i>
                <small>Error Message</small>
            </div>
            <div class="form_control" id="form_control">
                <label for="">重复密码</label>
                <input type="password" placeholder="请再次输入密码" id="password2">
                <i class="el-icon-success"></i>
                <i class="el-icon-warning"></i>
                <small>Error Message</small>
            </div>
            <button type="submit">Submit</button>
        </form>
    </div>

(2)CSS

* {
    
    
    box-sizing: border-box;
}

body {
    
    
    background-color: #9659b6;
    font-family: "Helvetica Neue", sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    margin: 0;
}

.container {
    
    
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    width: 400px;
    max-width: 100%;
}

.header {
    
    
    background-color: #f7f7f7;
    border-radius: 10px 10px 0 0;
    border-bottom: 1px soild #f0f0f0;
    padding: 20px 40px;
}

.header h2 {
    
    
    margin: 0;
}

.form {
    
    
    padding: 30px 40px;
}

.form_control {
    
    
    margin-bottom: 10px;
    padding-bottom: 20px;
    position: relative;
}

 .form_control label {
    
    
    display: inline-block;
    margin-bottom: 5px;
}
.form_control input {
    
    
    border: 2px solid #f0f0f0;
    border-radius: 4px;
    display: block;
    font-family: inherit;
    font-size: 14px;
    padding: 10px;
    width: 100%;
}


.form_control input:focus {
    
    
    outline: 0;
}

输入框验证的样式
.form_control.success input {
    
    
    border-color: #2ecc71;
}

.form_control.error input {
    
    
    border-color: #e74c3c;
}

/* 验证的图标的样式 */
.form_control.success i.el-icon-success {
    
    
    visibility: visible;
    color: #2ecc71;
}

.form_control.error i.el-icon-warning {
    
    
    visibility: visible;
    color: #e74c3c;
}

.form_control i {
    
    
    position: absolute;
    top: 40px;
    right: 10px;
    visibility: hidden;
}

.form_control small {
    
    
    visibility: hidden;
    position: absolute;
    font-weight: 600;
    bottom: 0;
    left: 0;
}

/* 验证错误的提示信息样式 */
.form_control.error small {
    
    
    visibility: visible;
    color: #e74c3c;
}

.form button {
    
    
    background-color: #8e44ad;
    border: 2px solid #8e44ad;
    border-radius: 5px;
    color: #fff;
    padding: 10px;
    width: 100%;
    font-size: 16px;
    display: block;
    transition: 0.3s;
}

.form button:hover {
    
    
    background-color: #fff;
    color: #8e44ad;
}

(3)JavaScript

<script>
        //获取页面实体(输入框、表单)---------------------------------------
        const form = document.getElementById("form");
        const username = document.getElementById("username");
        const email = document.getElementById("email");
        const passowrd = document.getElementById("password");
        const password2 = document.getElementById("password2");

        //form表单提交事件-----------------------------------
        form.addEventListener('submit', (e) => {
    
    
            checkInputs();
            e.preventDefault();//防止浏览器刷新页面提交表单
        })

        //总验证方法-------------------------------------------
        function checkInputs() {
    
    
            //获取输入框实体的输入值
            const usernameValue = username.value.trim();
            const emailValue = email.value.trim();
            const passwordValue = passowrd.value.trim();
            const password2Value = password2.value.trim();
            //用户名验证
            if (usernameValue==="") {
    
    
                setErrorFor(username, "用户名不能为空");
            } else {
    
    
                setSuccessFor(username);
            }
            //邮箱验证
            if(emailValue===""){
    
    
                setErrorFor(email,"邮箱不能为空");
            }else if(!valiEmail(emailValue)){
    
    //valiEmail返回的false表示邮箱不正确,则对其取反为true,if执行
                setErrorFor(email,"邮箱格式不正确,请重新输入");
            }else{
    
    
                setSuccessFor(email);
            }
            //密码验证
            if(passwordValue===""){
    
    
                setErrorFor(password,"密码不能为空");
            }else{
    
    
                setSuccessFor(passowrd)
            }
            //重复密码验证
            if(password2Value===""){
    
    
                setErrorFor(password2,"密码不能为空");
            }else if(passwordValue!==password2Value){
    
    
                setErrorFor(password2,"两次输入密码不一致,请再次输入")
            }else{
    
    
                setSuccessFor(password2)
            }
        }

        //简单封装验证成功和失败的方法-------------------------------
        //验证原理:输入框的父组件上添加成功或失败的样式,并且将验证错误信息动态添加到<small>标签中

        //验证失败
        function setErrorFor(input, message) {
    
    
            //input即为组件名(在这里因只有输入框所以写成input),message是错误信息(在总验证方法中传回错误信息message)
            const formControl = input.parentElement;//所验证实体(输入框)的父组件
            const small = formControl.querySelector('small');
            small.textContent = message;
            //此处须注意细节,如果只添加错误样式,输入错误信息后再次输入正确的信息,两个样式相互重叠,造成偏差,
            //所以之前应先去除已出现的样式,没明白的话,可以将添加success的代码注释掉,看看效果
            formControl.classList.remove('success');
            formControl.classList.add('error');
        }
        //验证成功
        function setSuccessFor(input) {
    
    
            const formControl = input.parentElement;
            //同理
            formControl.classList.remove('error');
            formControl.classList.add('success');
        }

        //邮箱验证特殊情况:邮箱格式不正确----------------------------
        function valiEmail(email){
    
    
            const regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            //将传过来的email值与定义的邮箱范围相比较
            return regEmail.test(email);//返回true或false
        }
    </script>
JS code logic

1. Get the page entity (input box, form), use getElementById()

//获取页面实体(输入框、表单)
const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const passowrd = document.getElementById("password");
const password2 = document.getElementById("password2");

2. form form submission event

//form表单提交事件
form.addEventListener('submit', (e) => {
    
    
     checkInputs();
     e.preventDefault();//防止浏览器刷新页面提交表单
})

3. Total Verification Method

//总验证方法
        function checkInputs() {
    
    
            //获取输入框实体的输入值
            const usernameValue = username.value.trim();
            const emailValue = email.value.trim();
            const passwordValue = passowrd.value.trim();
            const password2Value = password2.value.trim();
            //用户名验证
            if (usernameValue==="") {
    
    
                setErrorFor(username, "用户名不能为空");
            } else {
    
    
                setSuccessFor(username);
            }
            //邮箱验证
            if(emailValue===""){
    
    
                setErrorFor(email,"邮箱不能为空");
            }else if(!valiEmail(emailValue)){
    
    //valiEmail返回的false表示邮箱不正确,则对其取反为true,if执行
                setErrorFor(email,"邮箱格式不正确,请重新输入");
            }else{
    
    
                setSuccessFor(email);
            }
            //密码验证
            if(passwordValue===""){
    
    
                setErrorFor(password,"密码不能为空");
            }else{
    
    
                setSuccessFor(passowrd)
            }
            //重复密码验证
            if(password2Value===""){
    
    
                setErrorFor(password2,"密码不能为空");
            }else if(passwordValue!==password2Value){
    
    
                setErrorFor(password2,"两次输入密码不一致,请再次输入")
            }else{
    
    
                setSuccessFor(password2)
            }
        }

4. Simple encapsulation of methods for verifying success and failure

Validation principle : Add success or failure styles to the parent component of the input box, and dynamically add validation error information to the label.

setError method : the verification failure method, input is the component name (here, it is written as input because there is only an input box), and message is the error message (the error message message is returned in the total verification method). Attention must be paid to the details here. If you only add the wrong style, enter the correct information again after entering the wrong information, the two styles overlap each other, resulting in deviation. Therefore, you should remove the existing styles first. If you don’t understand, you can comment out the code that adds success to see the effect.

setSuccess method : the verification success method.

valiEmail method : email verification special case: the email format is incorrect, compare the passed email value with the defined email range, and return true or false.

        //简单封装验证成功和失败的方法
        //验证原理:输入框的父组件上添加成功或失败的样式,并且将验证错误信息动态添加到<small>标签中

        //验证失败
        function setErrorFor(input, message) {
    
    
            //input即为组件名(在这里因只有输入框所以写成input),message是错误信息(在总验证方法中传回错误信息message)
            const formControl = input.parentElement;//所验证实体(输入框)的父组件
            const small = formControl.querySelector('small');
            small.textContent = message;
            //此处须注意细节,如果只添加错误样式,输入错误信息后再次输入正确的信息,两个样式相互重叠,造成偏差,
            //所以之前应先去除已出现的样式,没明白的话,可以将添加success的代码注释掉,看看效果
            formControl.classList.remove('success');
            formControl.classList.add('error');
        }
        //验证成功
        function setSuccessFor(input) {
    
    
            const formControl = input.parentElement;
            //同理
            formControl.classList.remove('error');
            formControl.classList.add('success');
        }

        //邮箱验证特殊情况:邮箱格式不正确
        function valiEmail(email){
    
    
            const regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            //将传过来的email值与定义的邮箱范围相比较
            return regEmail.test(email);//返回true或false
        }

4. End

The above is the entire content of the form verification, please refer to it!

If you have any questions, you can private message, welcome to discuss!

The full version of the teaching demonstration video is at the address of station B , please pay attention to it, thank you, hehe.

Guess you like

Origin blog.csdn.net/m0_59420288/article/details/128186731