Vue项目的表单校验

目录

一、表单检验

二、步骤

三、前期准备

四、实战

(1)账号和密码的表单验证

(2)同意协议的表单验证

(3)整个表单内容验证


一、表单检验

1.作用:前端校验可以省去一些错误的请求提交,为后端节省接口压力

2.流程:

表单数据   =》  前端校验(过滤错误请求)  =》   后端查询是否匹配

3.工具:ElementPlus表单组件。https://element-plus.org/zh-CN/component/form.html

  • el-form(绑定表单和规则对象)
  • el-form-item(绑定使用的规则字段)
  • el-input(双向绑定表单数据)

当功能很复杂的时候,通过多个组件各自负责某个小功能,再组合成一个大功能

 

二、步骤

  1. 按照接口字段准备表单对象并绑定
  2. 按照产品要求准备规则对象并绑定
  3. 指定表单域的校验字段名
  4. 把表单对象进行双向绑定

用户名:不能为空,字段名为account

密码:不能为空且为6-14个字符,字段名为password

同意协议:勾选,字段名为agree

 

三、前期准备

在src文件夹下的views文件夹下创建一个Login文件夹,然后创建一个Index.vue文件,写入以下代码:

<script setup>
import { RouterLink } from 'vue-router';
import { ref } from 'vue';

</script>

<template>
  <div>
    <header class="login-header">
      <div class="container m-top-20">
        <h1 class="logo">
          <RouterLink to="/">小兔鲜</RouterLink>
        </h1>
        <RouterLink class="entry" to="/">
          进入网站首页
          <i class="iconfont icon-angle-right"></i>
          <i class="iconfont icon-angle-right"></i>
        </RouterLink>
      </div>
    </header>
    <section class="login-section">
      <div class="wrapper">
        <nav>
          <a href="javascript:;">账户登录</a>
        </nav>
        <div class="account-box">
          <div class="form">
            <el-form label-position="right" label-width="60px"
              status-icon>
              <el-form-item  label="账户">
                <el-input/>
              </el-form-item>
              <el-form-item label="密码">
                <el-input/>
              </el-form-item>
              <el-form-item label-width="22px">
                <el-checkbox  size="large">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subBtn">点击登录</el-button>
            </el-form>
          </div>
        </div>
      </div>
    </section>

    <footer class="login-footer">
      <div class="container">
        <p>
          <a href="javascript:;">关于我们</a>
          <a href="javascript:;">帮助中心</a>
          <a href="javascript:;">售后服务</a>
          <a href="javascript:;">配送与验收</a>
          <a href="javascript:;">商务合作</a>
          <a href="javascript:;">搜索推荐</a>
          <a href="javascript:;">友情链接</a>
        </p>
        <p>CopyRight &copy; 小兔鲜儿</p>
      </div>
    </footer>
  </div>
</template>

<style scoped lang='scss'>
.login-header {
  background: #fff;
  border-bottom: 1px solid #e4e4e4;

  .container {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
  }

  .logo {
    width: 200px;

    a {
      display: block;
      height: 132px;
      width: 100%;
      text-indent: -9999px;
      background: url("@/assets/images/logo.png") no-repeat center 18px / contain;
    }
  }

  .sub {
    flex: 1;
    font-size: 24px;
    font-weight: normal;
    margin-bottom: 38px;
    margin-left: 20px;
    color: #666;
  }

  .entry {
    width: 120px;
    margin-bottom: 38px;
    font-size: 16px;

    i {
      font-size: 14px;
      color: $xtxColor;
      letter-spacing: -5px;
    }
  }
}

.login-section {
  background: url('@/assets/images/login-bg.png') no-repeat center / cover;
  height: 488px;
  position: relative;

  .wrapper {
    width: 380px;
    background: #fff;
    position: absolute;
    left: 50%;
    top: 54px;
    transform: translate3d(100px, 0, 0);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);

    nav {
      font-size: 14px;
      height: 55px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      padding: 0 40px;
      text-align: right;
      align-items: center;

      a {
        flex: 1;
        line-height: 1;
        display: inline-block;
        font-size: 18px;
        position: relative;
        text-align: center;
      }
    }
  }
}

.login-footer {
  padding: 30px 0 50px;
  background: #fff;

  p {
    text-align: center;
    color: #999;
    padding-top: 20px;

    a {
      line-height: 1;
      padding: 0 10px;
      color: #999;
      display: inline-block;

      ~a {
        border-left: 1px solid #ccc;
      }
    }
  }
}

.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: $xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 20px 20px 20px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: $priceColor;
          }

          &.active,
          &:focus {
            border-color: $xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}

.subBtn {
  background: $xtxColor;
  width: 100%;
  color: #fff;
}
</style>

效果图:

 

四、实战

(1)账号和密码的表单验证

1.按照接口字段准备表单对象并绑定

(1)先准备好表单对象

// 1.准备表单对象
const form =ref({
  account: '',
  password: ''
})

(2)接着做一个绑定,对el-form组件进行一个绑定 :model

<el-form :model="form" label-position="right" label-width="60px" status-icon>

2.按照产品要求准备规则对象并绑定

(1)先准备规则对象

// 2.准备规则对象
const rules = {
  account : [
    {required:true , message:'用户名不能为空!' , trigger :'blur'}
  ],
  password : [
    {required: true ,  message:'密码不能为空!' , trigger :'blur'},
    {min :6 ,max : 14 , message:'密码长度是6-14位!' , trigger :'blur'},
  ]
}
  • required: true表示用户名(密码)是必须的,不能为空。
  • message: 是在验证失败时显示的错误消息。
  • trigger: 'blur'表示当用户离开输入框(失去焦点)时触发验证。
  • min:最小长度
  • max:最大长度

(2)对el-form进行规则对象绑定

<el-form :model="form" :rules="rules" label-position="right" label-width="60px" status-icon>

3.指定表单域的校验字段名

给el-form-item添加校验字段名prop="    "

 <el-form-item prop="account" label="账户">
      <el-input/>
 </el-form-item>
 <el-form-item prop="password" label="密码">
      <el-input/>
 </el-form-item>

4.把表单对象进行双向绑定

对el-input进行双向绑定v-model

<el-input v-model="form.account"/>
<el-input v-model="form.password"/>

5.验证看效果

 

我们可以发现,我们之前设置的验证规则都生效的,账号密码都不能为空,它们前面都带有星号 

 

(2)同意协议的表单验证

使用自定义校验规则,举个栗子

其中三个参数分别代表:

  • rule:验证的规则。
  • value:当前输入的数据。
  • callback:一个回调函数,用于在验证完成后执行。如果验证通过,通常会调用callback();如果验证失败,可能会调用callback(new Error('错误信息'))

同意协议的校验逻辑:如果勾选了,通过校验,反之。 

同样是我们的四个步骤走:

  • 按照接口字段准备表单对象并绑定
// 1.准备表单对象
const form =ref({
  account: '',
  password: '',
  agree: true
})

因为在上面我们已经对表单对象进行绑定了,这里就不需要了

​
 <el-form :model="form" :rules="rules" label-position="right" label-width="60px" status-icon>

​
  • 按照产品要求准备规则对象并绑定
// 2.准备规则对象
const rules = {
  account : [
    {required:true , message:'用户名不能为空!' , trigger :'blur'}
  ],
  password : [
    {required: true ,  message:'密码不能为空!' , trigger :'blur'},
    {min :6 ,max : 14 , message:'密码长度是6-14位!' , trigger :'blur'},
  ],
  agree : [
    {
      validator:(rule,value,callback) => {
        console.log(value);
        // 勾选就通过,不勾选就不通过
        if(value){
          callback()
        }else{
          callback(new Error('请勾选协议!'))
        }
      }
    }
  ]
}
  • 指定表单域的校验字段名
<el-form-item prop="agree" label-width="22px">
  • 把表单对象进行双向绑定
<el-checkbox v-model="form.agree" size="large">

看效果:

 

 

(3)整个表单内容验证

 问题:每个表单域都有自己的检验触发事件,如果用户一上来就点击登录怎么办?

 解决:在点击登录时需要对所有需要检验的表单进行统一检验。

 步骤:

  • 获取表单实例(先获取一个form实例,然后对其绑定)
// 3.获取form实例做同意校验
const formRef = ref(null)
<el-form ref="formRef" :model="form" :rules="rules" label-position="right" label-width="60px" status-icon>
  • 调用实例方法(先给登录按钮绑定一个doLogin方法,然后再去定义这个方法)
  • 17
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue Form表单校验是一种验证表单输入是否符合预期格式的技术。它的目的是为了提高用户填写表单的效率和准确性。在表单校验中,有三个关键要素:el-form上的model属性、el-form上的rules属性和el-form-item上的prop属性。 el-form上的model属性用于将表单的输入值与Vue实例中的数据进行绑定,实现双向数据绑定。这样可以方便地获取用户输入的值进行后续的处理和验证。 el-form上的rules属性是一个对象,用于定义表单项的验证规则。每个表单项可以有多个验证规则,如必填、长度限制、格式要求等。通过在rules属性中设置相应的规则,可以对表单项的输入进行校验。 el-form-item上的prop属性是用来指定与rules属性中对应的验证规则的字段名。通过指定prop属性,可以将验证规则与具体的表单项进行关联,从而实现对单个表单项的校验。 使用Vue Form表单校验可以有效地提高表单填写的准确性和效率,避免了用户多次提交和服务器多次返回错误的情况,提升了用户体验。通过合理设置model、rules和prop属性,可以实现对表单输入的全面校验,保证数据的准确性和完整性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue-form表单验证是否为空值的实例详解](https://download.csdn.net/download/weixin_38655484/12933221)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [VUE项目中如何进行表单校验](https://blog.csdn.net/m0_57524265/article/details/130929210)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值