Form data validation hook with fp-ts and functional programming

Sandro Maglione

Sandro Maglione

Web development

When you are working with users' input, things will get tricky.

useState does not validate your data correctly, it is unsafe. useStateValidation instead gives you access to the user input only if the format is valid.

This hook uses fp-ts and functional programming, specifically the Either type. You need to provide both an initial value (just like a normal useState hook) as well as a validation function. The validation function returns Right when the input data is valid, and Left otherwise.

By using this hook, you guarantee that your data is always valid.

import * as E from "fp-ts/Either";
import { Dispatch, SetStateAction, useState } from "react";
export const useStateValidation = <InputValue, ValidValue, ErrorType>(
  initialValue: InputValue,
  validate: (i: InputValue) => E.Either<ErrorType, ValidValue>
): [
  E.Either<ErrorType, ValidValue>,
  () => void
] => {
  const [isDirty, setIsDirty] = useState<boolean>(false);
  const [value, setValue] = useState<InputValue>(initialValue);
  const setValueDirty: Dispatch<SetStateAction<InputValue>> = (v) => {
  const reset = () => {
  return [value, setValueDirty, validate(value), isDirty, reset];

👋・Interested in learning more, every week?

Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 700+ readers.