Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

vue.js - ElementUI doing validation with Sub Component

How to validate a sub component inside a form?

In the form component I have the sub component:

<template>
  <el-form :model="value">
    <el-form-item 
      prop="name" 
      :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
    >
      <el-input v-model="value.name">
    </el-form-item>
    <ZipCode v-model="value.zipcode" />
  </el-form>
</template>
<script>
export default {
  props: {
    value: { 
      type: Object, 
      default: () => { 
        return { 
          name: null, 
          zipcode: { code: null, local: null }
        } 
      }
    }
  }
}
</script>

And in the ZipCode component:

<template>
  <el-form-item 
    prop="code" 
    :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
  >
    <el-input v-model="value.code">
  </el-form-item>

  <el-form-item 
    prop="local" 
    :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
  >
    <el-input v-model="value.local">
  </el-form-item>
</template>
<script>
export default {
  props: {
    value: { 
      type: Object, 
      default: () => { return { code: null, local: null } } 
    }
  }
}
</script>

The validation on the form component is working as expected but not the validation on the sub component. If the field has data, still gives the error that data is required. This false validation is also working from the form component.

So problem might be on the "prop" field. If change the prop to "value.code" or "zipcode.code" it gives the error "Error: please transfer a valid prop path to form item".

What might be the issue? Thank you for any help.

question from:https://stackoverflow.com/questions/66063682/elementui-doing-validation-with-sub-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The rule should have the type as an 'object' with a fields property for each sub rule.

  <el-form :model="value" :rules="
    {
      name: [
        { required: true, message: 'Please input name', trigger: 'blur' }
      ],
      zipcode: {
        type: 'object',
        required: true,
        fields: {
          code: { type: 'string', required: true, len: 8, message: 'invalid zip' },
          local: { type: 'string', required: true, message: 'required' }
        }
      }
    }
  ">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...