Skip to content

Get Form Data in Validation Rules

In FormCreate, the this context of the validator method has been modified to include an api property. Through this.api, developers can access the form API to get or manipulate values of other fields.

Configuration Example

The following example shows how to use the form API in validation rules to achieve cross-validation, where the validation of one field value depends on the value of another field.

Example Code

js
const rules = [
  {
    type: 'input',
    field: 'cost_price',
    title: 'Cost Price',
  },
  {
    type: 'input',
    field: 'goods_price',
    title: 'Price',
    validate: [
      {
        required: true,
        validator(val, rule, callback) {
          const api = this.api; // Get form API instance
          const costPrice = api.getValue('cost_price'); // Get the value of the cost_price field through the API
          // Simple validation logic: price cannot be lower than cost price
          if (val < costPrice) {
            callback(new Error('Price cannot be lower than cost price'));
          } else {
            callback(); // Validation passed
          }
        }
      }
    ]
  }
];

Explanation

  • Field Definition: The form contains two input boxes: cost_price (cost price) and goods_price (price).
  • Cross-validation: In the validation rule of the goods_price field, get the value of the cost_price field using this.api.
  • Custom Validation Logic: If the entered price is less than the cost price, pass an error message through callback to trigger validation failure; otherwise, call callback() to indicate validation passed.

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.