Custom Control Validation in AntD

From Logic Wiki
Jump to: navigation, search


In the component

Import forwardRef from react

import React, { Fragment, useState, useEffect, forwardRef } from "react";

at the end of the file before export it add this forwardRef line

IndemnityLimits = forwardRef(IndemnityLimits);
export default Form.create()(IndemnityLimits);

In the page

Write custom validation function In the page where you consume the component. Parameters are fixed. If you need to pass more then one value use object or array like below

    const checkIndemnity = (rule, value, callback) => {
        if (value && value[0] && value[1] && value[2]) {
            callback();
            return;
        }
        callback("Indemnity limits must be selected!");
    }

Use the validation in getFieldDecorator

<Form.Item label={question.questionName} key={fieldId} className={classname}>
                    {getFieldDecorator(fieldId, { initialValue: data[fieldId], rules: [{ validator: checkIndemnity }] })(
                        <IndemnityLimit
                            …
                        </IndemnityLimit>
                    )}
                </Form.Item>

In the component

Validator comes to props as onChange

function IndemnityLimits(props, ref) {
...
    let validationArray = [true, true, true]
prepare the values to send them back to validate function and pass them via props.onChange
const validatate = (rg) => {
        if (rg == "RGD") {
            validationArray = [true, validationArray[1], validationArray[2]]
        }
        if (rg == "RGE") {
            validationArray = [validationArray[0], true, validationArray[2]]
        }
     ...
        props.onChange(validationArray);
    }

Call validate function in the component

 const updateSelectedValues = (rg, name, value) => {
        validatate(rg);
    }

 <input type="radio"
    key={limitName + k.indemnityId}
    name={limitName}
    value={k.indemnityId}
    onChange={() => updateSelectedValues(limitName, fieldId + "A" + limitName, k.indemnityId)}

see https://codesandbox.io/s/kind-tharp-ppofz