Form Validation Examples

Form Validation Examples

Here you can find examples of form validation. Both examples use the same Zod schema and the same controller.

Live Example for Basic Form vaidation using Zod

/src/app/form/FormExample.tsx
'use client';
import { useState, type FormEvent } from 'react';
import { FormController } from 'vovk-client';
import type { VovkReturnType } from 'vovk';
 
export default function FormExample() {
  const [response, setResponse] = useState<VovkReturnType<typeof FormController.createUser> | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [disableClientValidation, setDisableClientValidation] = useState(false);
  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      setResponse(
        await FormController.createUser({
          body: { name, email },
          disableClientValidation,
        })
      );
      setError(null);
    } catch (e) {
      setError(e as Error);
      setResponse(null);
    }
  };
 
  return (
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
      <input type="text" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <label className="block mb-4">
        <input
          type="checkbox"
          className="mr-2"
          checked={disableClientValidation}
          onChange={(e) => setDisableClientValidation(e.target.checked)}
        />
        Disable client-side validation
      </label>
      <button>Submit</button>
 
      {response && (
        <div className="text-left">
          <h3>Response:</h3>
          <pre>{JSON.stringify(response, null, 2)}</pre>
        </div>
      )}
 
      {error && <div className="overflow-auto">❌ {String(error)}</div>}
    </form>
  );
}

Source code (opens in a new tab)

Live Example of a Form validation using react-hook-form and Zod

/src/app/hook-form/HookFormExample.tsx
'use client';
import { useState } from 'react';
import { FormController } from 'vovk-client';
import { useForm } from 'react-hook-form';
import type { VovkBody, VovkReturnType } from 'vovk';
import { zodResolver } from '@hookform/resolvers/zod';
import { userSchema } from '../../zod';
 
export default function HookFormExample() {
  const [response, setResponse] = useState<VovkReturnType<typeof FormController.createUser> | null>(null);
  const {
    register,
    handleSubmit,
    getValues,
    formState: { errors },
  } = useForm<VovkBody<typeof FormController.createUser>>({
    resolver: zodResolver(userSchema),
  });
 
  const onSubmit = async () => {
    setResponse(
      await FormController.createUser({
        body: getValues(),
      })
    );
  };
 
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="Name" {...register('name')} />
      {errors.name && <p>❌ {errors.name.message}</p>}
      <input type="text" placeholder="Email" {...register('email')} />
      {errors.email && <p>❌ {errors.email.message}</p>}
      <button>Submit</button>
 
      {response && (
        <div>
          <h3>Response</h3>
          <pre className="text-left">{JSON.stringify(response, null, 2)}</pre>
        </div>
      )}
    </form>
  );
}

Source code (opens in a new tab)