Field methods

validate

Arguments: (opts)

Validates the field if it is not omitted (See Hiding and showing fields).

These buttons are outside of the ChangesetWebform component
import React from 'react';
import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods1',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleOne() {
  const nameFieldRef = React.useRef(null);

  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.fields.find((field) => field.fieldId === 'name');
  }

  async function externalValidation() {
    await nameFieldRef.current.validate();
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">These buttons are outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <button
            data-test-id="validate-externally"
            className="btn btn-primary me-2"
            type="button"
            onClick={externalValidation}
          >
            Validate name field externally
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}

If you would like to only revalidate fields which have already been validated, set opts.skipUnvalidated to true.

These buttons are outside of the ChangesetWebform component
import { useRef, useReducer } from 'react';
import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods2',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name (Min 3 chars)',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
        {
          validationMethod: 'validateLength',
          arguments: {
            min: 3,
            // max: 3,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleTwo() {
  const nameFieldRef = useRef(null);
  const [, forceUpdate] = useReducer((n) => n + 1, 0);

  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.fields.find((field) => field.fieldId === 'name');
  }

  async function externalValidation() {
    nameFieldRef.current.updateValue('New Name');
    await nameFieldRef.current.validate({ skipUnvalidated: true });
    forceUpdate();
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">These buttons are outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <button
            data-test-id="validate-externally"
            className="btn btn-primary me-2"
            type="button"
            onClick={externalValidation}
          >
            Validate externally
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}

setOmission

Allows you to updated whether the field is omitted by passing a boolean value.

See /docs/hiding-and-showing-fields#the-setomission-method.

These buttons are outside of the ChangesetWebform component
import { useRef, useReducer } from 'react';

import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods3',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleThree() {
  const nameFieldRef = useRef(null);
  const [_, forceUpdate] = useReducer((n) => n + 1, 0);
  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.fields.find((field) => field.fieldId === 'name');
  }

  function toggleOmission() {
    nameFieldRef.current.setOmission(!nameFieldRef.current.isOmitted);
    forceUpdate();
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">These buttons are outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <button
            data-test-id="toggle-name-field"
            className="btn btn-primary me-2"
            type="button"
            onClick={toggleOmission}
          >
            Toggle field
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}

updateValue

Arguments: (value)

Updates the value of the field.

The value argument is the value to update the field to.

These buttons are outside of the ChangesetWebform component
import { useRef, useReducer } from 'react';
import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods4',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleFour() {
  const nameFieldRef = useRef(null);
  const [_, forceUpdate] = useReducer((n) => n + 1, 0);

  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.fields.find((field) => field.fieldId === 'name');
  }

  function updateNameField() {
    nameFieldRef.current.updateValue('New Name');
    forceUpdate();
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">These buttons are outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <button
            data-test-id="update-name-field"
            className="btn btn-primary me-2"
            type="button"
            onClick={updateNameField}
          >
            Update value of name field
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}

reset

Discards any unsaved changes to the field's value, and unvalidates the field.

These buttons are outside of the ChangesetWebform component
import React from 'react';
import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods6',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name',
      defaultValue: 'Default Name',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleSix() {
  const nameFieldRef = React.useRef(null);

  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.fields.find((field) => field.fieldId === 'name');
  }

  function resetNameField() {
    nameFieldRef.current.reset();
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">These buttons are outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <button
            data-test-id="reset-name-field"
            className="btn btn-primary me-2"
            type="button"
            onClick={resetNameField}
          >
            Reset name field
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}

pushErrors

Allows you to push errors onto a field. This will force the field to show the error and display as invalid in the UI.

This input is outside of the ChangesetWebform component
import { useRef, useReducer } from 'react';
import ChangesetWebform from 'react-changeset-webforms/src/components/ChangesetWebform.jsx';

const formSchema = {
  formSettings: {
    formName: 'fieldMethods7',
    hideSubmitButton: true,
  },
  fields: [
    {
      fieldId: 'name',
      fieldType: 'input',
      fieldLabel: 'Name',
      defaultValue: 'Default Name',
      validationRules: [
        {
          validationMethod: 'validatePresence',
          arguments: {
            presence: true,
          },
        },
      ],
    },
  ],
};

export default function FieldMethodsExampleSeven() {
  const nameFieldRef = useRef(null);
  const [_, forceUpdate] = useReducer((n) => n + 1, 0);
  function afterGenerateChangesetWebform(changesetWebform) {
    nameFieldRef.current = changesetWebform.getField('name');
  }

  function pushErrors() {
    nameFieldRef.current.pushErrors(['This is a custom error message']);
    forceUpdate();
  }

  function updateErrorMessage(event) {
    nameFieldRef.current.pushErrors([event.target.value]);
    document.querySelector('[data-test-id="error-message-input"]').value = '';
    forceUpdate();
  }

  function handleErrorMessageKeyDown(event) {
    if (event.key === 'Enter') {
      updateErrorMessage(event);
    }
  }

  return (
    <>
      <div className="border rounded p-2 mb-4 bg-light">
        <b className="mb-2">This input is outside of the ChangesetWebform component</b>
        <div className="d-flex mt-2">
          <input
            type="text"
            placeholder="Error message"
            className="form-control me-2"
            style={{ maxWidth: '300px' }}
            data-test-id="error-message-input"
            onBlur={updateErrorMessage}
            onKeyDown={handleErrorMessageKeyDown}
          />
          <button
            className="btn btn-primary me-2"
            type="button"
            onClick={pushErrors}
          >
            Push error to name field
          </button>
        </div>
      </div>
      <ChangesetWebform
        formSchema={formSchema}
        afterGenerateChangesetWebform={afterGenerateChangesetWebform}
      />
    </>
  );
}