Validation

Rule

The library exposes the Rule component that you need to use to implement your rule. For example, there is a simple rule to check if a value is defined.

const isNullOrUndefined = (x: unknown): x is null | undefined => x === null || x === undefined;

const isEmpty = (value: unknown): value is '' => value === '';

const isRequired = (value: unknown) => !isNullOrUndefined(value) && !isEmpty(value);

const RuleIsRequired = () => {
  return <Rule message="This field is required" validationFn={isRequired} />;
}


// In you component
<Field
      name={name}
      render={(fieldProps) => {
        const { onBlur, onChange, onFocus, value } = fieldProps;

        const handleChange: InputHTMLAttributes<HTMLInputElement>['onChange'] =
          (e) => {
            onChange(e.target.value);
          };

        return (
          <input
            onChange={handleChange}
            onBlur={onBlur}
            onFocus={onFocus}
            value={value}
          />
        );
      }}
    >
      <RuleIsRequired /> {/* The field is now a required field */}
</Field>

You can use the rule inside each Field of the library. Rule will be checked on blur.

Hooks

useValidations

The useValidations hook allows you to watch the validation status of specific fields or all fields in a form.

import { useValidations, useFormContext } from 'graneet-form';

function ValidationDisplay() {
  const form = useFormContext();
  
  // Watch specific fields
  const validations = useValidations(form, ['email', 'password']);
  
  // Watch all fields
  const allValidations = useValidations(form);

  return (
    <div>
      {Object.entries(validations).map(([fieldName, validation]) => (
        <div key={fieldName}>
          <strong>{fieldName}:</strong>
          <span className={validation?.status === 'VALID' ? 'valid' : 'invalid'}>
            {validation?.status} - {validation?.message}
          </span>
        </div>
      ))}
    </div>
  );
}

useFormStatus

The useFormStatus hook provides the overall validation status of the form.

import { useFormStatus, useFormContext } from 'graneet-form';

function FormStatus() {
  const form = useFormContext();
  const { formStatus, isValid } = useFormStatus(form);

  return (
    <div>
      <p>Form Status: {formStatus}</p>
      <p>Is Valid: {isValid ? 'Yes' : 'No'}</p>
      <button disabled={!isValid} type="submit">
        Submit Form
      </button>
    </div>
  );
}

The form status can have three values:

  • VALID: All fields are valid
  • INVALID: At least one field is invalid
  • UNDETERMINED: Some fields haven't been validated yet

Example