InfoStatus
InfoStatus

Reputation: 7113

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.

Upvotes: 2

Views: 4756

Answers (1)

InfoStatus
InfoStatus

Reputation: 7113

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' }
        }
      }
    }
  ">

Upvotes: 1

Related Questions