Issue with Upload Component Validation in Kendo Form

1 Answer 28 Views
Form Upload
Tejas
Top achievements
Rank 2
Iron
Iron
Iron
Tejas asked on 18 Feb 2025, 07:33 AM

I’m using a Kendo form and rendering it dynamically. I’m facing an issue with the upload component validation. For example, when creating a new record, a validation error shows up if the file is not uploaded. However, after the data is saved and when I edit the record, if any other fields are changed, the validation error appears for those fields. What I want is to skip the validation for the upload component while editing, so the form can be submitted without it, but the validation should still be enforced during creation.

I am using these type off code

 [{
    id: 'clusterCode',
    name: 'clusterCode',
    label: 'Cluster Code',
    required: true,
    type: 'text',
    fieldType: 'Input',
    validator: requiredValidator,
  },
  {
    id: 'clusterName',
    name: 'clusterName',
    label: 'Cluster Name',
    type: 'text',
    fieldType: 'Input',
    required: true,
    validator: requiredValidator,
  },]

 

these type data can be use and these my form code 

/** @format */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Field,
  FieldRenderProps,
  FieldValidatorType,
  Form as OkForm,
} from '@progress/kendo-react-form';
import { Button } from '@progress/kendo-react-buttons';
import { LABEL_CANCEL, LABEL_STAR, LABEL_SUBMIT } from '@constants/Common';
import { MultiSelect } from '@progress/kendo-react-dropdowns';
import { FormComponent } from './FormComponent';
import './form.css';
type FormFieldInit = {
  restrictions?: any;
  hint?: unknown;
  note?: unknown;
  readonly?: unknown;
  id?: string;
  type: string;
  dataItemKey?: string;
  defaultItem?: string;
  textField?: unknown;
  required?: unknown;
  data?: unknown;
  options?: string;
  fieldType?: string;
  name: string;
  label?: string;
  validator?: FieldValidatorType;
  colSpan?: number;
  rowSpan?: number;
  rows?: number;
  requiredHint?: boolean;
};
interface FormProps {
  formField: FormFieldInit[];
  editValue: { [key: string]: unknown };
  formOnchange: (
    event: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => void;
  formaStyle: React.CSSProperties;
  handleSubmit: (data: { [key: string]: unknown }) => void;
  formRef: React.RefObject<HTMLFormElement>;
}
const CustomField = ({ label }: { label: string }) => (
  <div className='form-group'>
    <label>
      <span>{label}</span>
      <span style={{ color: 'red' }}> {LABEL_STAR}</span>
    </label>
  </div>
);
function Form({
  formField,
  editValue,
  formOnchange,
  formaStyle,
  handleSubmit,
  formRef,
}: FormProps) {
  const [initialValues, setInitialValues] = useState<Object>({});
  const {
    FormDropDownList,
    FormInput,
    FormDateTimePicker,
    FormCheckbox,
    FormTextArea,
    FormDatePicker,
    FormMaskedInputWithCountryCode,
    FormUpload,
  } = FormComponent();
  const fieldComponents: {
    [key: string]: React.ComponentType<FieldRenderProps>;
  } = {
    Input: FormInput,
    TextArea: FormTextArea,
    Dropdown: FormDropDownList,
    MultiSelector: MultiSelect,
    DatePicker: FormDatePicker,
    Checkbox: FormCheckbox,
    Upload: FormUpload,
  };
  useEffect(() => {
    const generatedValues = formField.reduce(
      (acc, field) => ({
        ...acc,
        [field.name]: editValue?.[field.name] || '',
      }),
      {}
    );
    setInitialValues(generatedValues);
  }, [editValue, formField]);
  return (
    <OkForm
      ref={formRef}
      initialValues={initialValues}
      onSubmit={handleSubmit}
      key={JSON.stringify(initialValues)}
      render={(formRenderProps) => (
        <div>
          <div
            style={{
              ...formaStyle,
            }}
          >
            {formField.map((items, index) => {
              const FieldComponent = fieldComponents[items.fieldType];
              return (
                <div
                  style={{
                    gridColumn: items.colSpan
                      ? `span ${items.colSpan}`
                      : 'span 1',
                  }}
                  key={index}
                >
                  <Field
                    id={items.id}
                    name={items.name}
                    component={FieldComponent}
                    label={
                      items.required === true ? (
                        <CustomField label={items.label} />
                      ) : (
                        items.label
                      )
                    }
                    validator={items.validator}
                    data={items.data}
                    required={items.required}
                    textField={items.textField}
                    defaultItem={items.defaultItem}
                    filterable={true}
                    dataItemKey={items.dataItemKey}
                    onChange={formOnchange}
                    readonly={items.readonly}
                    props={{
                      ...(items.fieldType === 'Dropdown' ||
                      items.fieldType === 'MultiSelector' ||
                      items.fieldType === 'DatePicker' ||
                      items.fieldType === 'Checkbox'
                        ? { data: items.options }
                        : {}),
                    }}
                    note={items.note}
                    customHint={items.hint}
                    type={items.type}
                    restrictions={items.restrictions}
                    rows={items.rows}
                    requiredHint={items.requiredHint}
                  />
                </div>
              );
            })}
          </div>
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(4,1fr)',
              gap: '25px',
              flexWrap: 'wrap',
              marginTop: 20,
              maxWidth: '456px',
            }}
          >
            <Button
              onClick={() => {
                formRef.current.resetForm();
                setInitialValues({});
              }}
            >
              {LABEL_CANCEL}
            </Button>
            <Button
              themeColor='primary'
              disabled={!formRenderProps.allowSubmit}
              onClick={formRenderProps.onSubmit}
            >
              {LABEL_SUBMIT}
            </Button>
          </div>
        </div>
      )}
    />
  );
}
export default Form;

1 Answer, 1 is accepted

Sort by
0
Yanko
Telerik team
answered on 19 Feb 2025, 08:00 PM

Hello, Tejas,

I can suggest the following approach in order to apply validation for the Upload only when creating a record.

  1. Add a Mode Prop: Ensure you have a way to determine whether the form is in "create" or "edit" mode. You can pass a custom mode prop to your form component to handle this.
  2. Conditional Validator Assignment: Modify the validator assignment for the upload field to apply only when in "create" mode.

Please let me know if such an approach is viable in your scenario. In case I can further assist you, please provide additional details and if possible an example replicating this behaviour. 

Regards,
Yanko
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
Form Upload
Asked by
Tejas
Top achievements
Rank 2
Iron
Iron
Iron
Answers by
Yanko
Telerik team
Share this question
or