DDBS UI
modals

Form Field and Validation

FormField, TextField (input or textarea) and useValidatedForm with required, email, minLength, phone and combine validators. Errors show on blur or on a submit attempt, and the first invalid field gets focus.

npx shadcn@latest add https://ui.develop-better-solutions.com/r/form-field.json
Fullscreen

With country code.

Usage

form-field-example.tsx
"use client";

import { useMemo, useState } from "react";
import { TextField, ruleAll, ruleEmail, ruleMinLength, rulePhone, ruleRequired, useValidatedForm } from "@dbs/ui";

export default function FormFieldExample() {
  const rules = useMemo(() => ({ name: ruleRequired(), email: ruleAll(ruleRequired(), ruleEmail()), phone: rulePhone(), message: ruleMinLength(10) }), []);
  const form = useValidatedForm({ name: "", email: "", phone: "", message: "" }, rules);
  const [sent, setSent] = useState(false);
  const submit = form.handleSubmit(() => setSent(true));
  if (sent) return <p role="status" className="rounded-2xl border border-line bg-surface px-5 py-4 text-sm">Thanks, the form passed validation. <button type="button" className="underline" onClick={() => { form.reset(); setSent(false); }}>Reset</button></p>;
  return (
    <form noValidate onSubmit={submit} className="grid w-full max-w-xl gap-4">
      <div className="grid gap-4 sm:grid-cols-2">
        <TextField id="ff-name" label="Name" required autoComplete="name" {...form.field("name")} />
        <TextField id="ff-email" label="Email" type="email" required autoComplete="email" {...form.field("email")} />
      </div>
      <TextField id="ff-phone" label="Phone" type="tel" hint="With country code." autoComplete="tel" {...form.field("phone")} />
      <TextField id="ff-message" label="Message" rows={4} {...form.field("message")} />
      <button type="submit" className="h-12 rounded-full bg-ink text-sm font-medium text-canvas">Send</button>
    </form>
  );
}