大家好,今天分享一个HTML+CSS+JS表单验证,这是我前两天学习一个demo,在这记录一下。

目录

一、效果图

二、介绍

三、代码

(1)HTML

(2)CSS

(3)JavaScript

         JS代码逻辑:

四、结束

一、效果图

 

 二、介绍

图标库使用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>

地址组件 | Element ,也可使用其他组件库,根据自己的喜好。

三、代码

(1)HTML

<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;
    /* box-shadow: 0 4px 2px rgba(0,0,0,0.3); */
    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.addEventListener('submit', (e) => {
            e.preventDefault();
            checkInputs();
        })
        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)){
                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)
            }
        }
        function setErrorFor(input, message) {
            const formControl = input.parentElement;
            const small = formControl.querySelector('small');
            small.textContent = message;
            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})$/;
            return regEmail.test(email);
        }
    </script>

JS代码逻辑

1.获取页面实体输入框表单),使用 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.addEventListener('submit', (e) => {
            e.preventDefault();//防止浏览器新页面提交表单
            checkInputs();
        })

3.总验证方法

        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.简单封装验证成功和失败方法

验证原理输入框的父组件上添加成功或失败的样式,并且将验证错误信息动态添加到<small>标签中。

setError方法:验证失败方法,input即为组件名(在这里因只有输入框所以写成input),message错误信息(在总验证方法中传回错误信息message)。此处须注意细节,如果只添加错误样式,输入错误信息后再次输入正确的信息,两个样式相互重叠,造成偏差。所以之前应先去除已出现的样式,没明白的话,可以将添加success的代码注释掉,看看效果

setSuccess方法验证成功方法

valiEmail方法:邮箱验证特殊情况:邮箱格式正确,将传过来的email值与定义的邮箱范围比较返回truefalse

        //验证失败
        function setErrorFor(input, message) {
            const formControl = input.parentElement;//所验证实体(输入框)的父组件
            const small = formControl.querySelector('small');
            small.textContent = message;
            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);//返回truefalse
        }

四、结束

以上为表单验证的全部内容,请大家参考

如有问题私信,欢迎探讨!

原文地址:https://blog.csdn.net/qq_51336762/article/details/126577159

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_34908.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注