form表单验证

form表单校验

表单中设置必选项,当必选项未填信息时弹出指定的错误信息,阻止用户提交请求。
在这里插入图片描述

1.在html种写弹框
:ref 绑定控件,$refs 获取控件 (*该例中不带冒号绑定选择直接传参)
:model=“绑定数据”
:rules=“验证规则”

<el-dialog title="添加申请" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false" :before-close="handleClose">
            <el-form  ref="submitForm" :model="submitForm" :rules="ruless" label-width="30%" label-position="left" class="form-div" size="small">
                <el-form-item label="name" prop="name">
                    <el-input v-model="submitForm.name" prop="name" size="small" placeholder="请输入name"></el-input>
                </el-form-item>
                <el-form-item label="password" prop="password">
                    <el-input v-model="submitForm.password" size="small" placeholder="请输入password" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="remove()">取 消</el-button>
                <el-button @click="reset('submitForm')">重置</el-button>
                <el-button type="primary" @click="sure('submitForm')">确 定</el-button>
                
            </span>
        </el-dialog>

2.在data种定义绑定的对象,声明规则
ruless:每一条对象对应一个必选项,required为true时显示星号(*),message:弹出的错误信息。

data() {
        return {
            submitForm:{
                name:'',
                password:'',
            },
            ruless: {
                name: [{ required: true, message: '请输入name', trigger: 'blur' }],
                password: [{ required: true, message: '请输入password', trigger: 'blur' }],
            },
            dialogVisible:false,
         }

3.method方法中写函数

methods: {
        //button按钮点击弹出弹框
        test(){
            this.dialogVisible = true
        },
        //确认添加
        sure(submitForm){
            this.$refs[submitForm].validate((valid) => {
                console.log(valid)
             if (valid) {
                alert('验证通过!');
               //可写执行添加的方法
            } else {
            console.log('验证失败!');
            return false;
          }
        });
        },
        //重置表单
        reset(submitForm) {
          this.$refs[submitForm].resetFields();
        },
        //取消表单
         remove() {
            this.$refs.form.resetFields()//表单验证在关闭时恢复初始值
            this.dialogVisible = false;
            submitForm={
                name:'',
                password:'',
            },
            this.editFlag = false; 
        },
   }

完结。。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值