Field-wise validation status in custom Antd/Vue.js form component

55 views Asked by At

To illustrate the problem I'll use example from Antdv documentation. When using their custom price-input component (which consists of input and select fields and binds their values in one object) in a Form.Item with validation rule and validation fails, both price-input fields are highlighted in red. How is it possible to make custom component validation status more selective, i.e. if the validation failed on price.number value, so only corresponding input field be highlighted?

So far I had two ideas:

  • to implement validation logic inside the component and set status of nested fields manually,
  • to pass an object with statuses of all fields, something like hasError = {number: true, currency: false} and update it from outside,

but both ideas seems to ignore Form.Item and its validation rules mechanism.

<template>
  <a-form
    name="customized_form_controls"
    layout="inline"
    :model="formState"
    @finish="onFinish"
  >
    <a-form-item
      name="price"
      label="Price"
      :rules="[{ validator: checkPrice }]"
    >
      <price-input v-model:value="formState.price" />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import PriceInput from "./PriceInput.vue";

export default {
  data() {
    return {
      formState: {
        price: {
          number: 0,
          currency: "rmb",
        },
      },
    };
  },
  components: {
    PriceInput,
  },
  methods: {
    onFinish(values) {
      console.log("Received values from form: ", values);
    },
    checkPrice(_, value) {
      if (value.number > 0) {
        return Promise.resolve();
      }
      return Promise.reject(new Error("Price must be greater than zero!"));
    },
  },
};
</script>

Edit Custom form component validation

0

There are 0 answers