How to use rules form verification rules in vue: rules="rules"

1. Attribute values ​​must be written in el-form

:ref="dataForm" // Verify when submitting the form

: Rules = & Quot; Rules & Quot; // The verification rules under the Return
: Model = & Quot; Userform & Quot; // Binding the value of the form

<el-form
  ref="dataForm"     // 必写属性值
  :rules="rules"     // 必写属性值
  :model="userForm"  // 必写属性值
  label-position="left"
  label-width="100px"
>
  <el-row>
    <el-col :span="12">
      <el-form-item
        label="充值金额"
        prop="amount"  // 必写属性值
      >
        <el-input
          v-model="userForm.amount"  // 必写属性值
          placeholder="请输入充值金额"
        ></el-input>
      </el-form-item>
    </el-col>
  </el-row> 
</el-form>
<div slot="footer" class="dialog-footer" align="center">
  <el-button @click="dialogFormVisible = false">返回</el-button>
  <el-button type="primary" @click="Recharge()" >
    提交
  </el-button>
</div>

2. :ref Verification when submitting the form

When you click submit, the value of the form will be verified and judged first. After the verification is passed, subsequent operations will be carried out.

Recharge() {
  this.$refs['dataForm'].validate((valid) => {
    if (valid) {
      // 校验通过、调充值接口的逻辑操作
  }
})

3. :rules verification rules

el-form-item uses prop attribute binding rules

<el-form-item label="Recharge amount" prop="amount"> ... ... </el-form-item>

required: Displays the input box as optional or required;
message: Prompt message;

pattern: regular expression;

Trigger: Trigger event => Generally blur is used for input, change is used for select, picker, etc.;

data() {
  return { 
    rules: {
      amount: [
        { required: true, message: '充值金额不能为空', trigger: 'blur' },
        {
          pattern: /^\d+(\.\d{1,1})?$/,
          message: '金额为数字类型且最多保留1位小数',
          trigger: 'blur',
        },
      ],
    },
  }
},

4. :model binds the value of the form

el-input uses v-model to bind form values

<el-input  v-model="userForm.amount" ></el-input>

data() {
  return {
    userForm: {
      amount: '',
    }, 
  }
},
 

question:

The verification failed, and there are still problems when closing the pop-up window and opening it again:

 this.dialogFormVisible = true
 this.$nextTick(() => {
   this.$refs['dataForm'].clearValidate()
 })

Guess you like

Origin blog.csdn.net/m0_61663332/article/details/134214443