Example: Basic Form

In this example we show how to use the CruddyForms typescript module to create a simple form with client-side validation and serve it from your website.
    1
  • Define the schema using Typebox

        // ~/examples/basic/schema.ts
    import {Type} from "@sinclair/typebox";
    import type {FormInputCheckbox, FormInputText, FormTextArea} from "cruddy-forms";
    
    export const UsernameSchema = Type.Object( {
      username: Type.RegExp(
        /^\S*$/, // No whitespace
          {
            element: "input",
            hint: "Username may not contain spaces",
            inputType: "text",
            maxLength: 8,
            placeholder: "your username",
          } satisfies FormInputText,
        ),
    } );
    
    const EmailSchema = Type.Object( {
      email: Type.RegExp(
        /.+@example\.com/i,
          {
            element: "input",
            hint: "Must end in @example.com",
            inputType: "email",
            placeholder: "[email protected]",
          } satisfies FormInputText,
        ),
    } );
    
    const PASS_MIN = 6;
    const PasswordSchema = Type.Object( {
      password: Type.String( {
        element: "input",
        hint: `Use ${PASS_MIN} or more characters`,
        inputType: "password",
        minLength: PASS_MIN,
        placeholder: "your password",
        } satisfies FormInputText ),
    } );
    
    const CommentSchema = Type.Object( {
        comment: Type.String( {
            element: "textarea",
            inputType: "text",
            maxLength: 50,
            minLength: 10,
            rows: 5,
            } satisfies FormTextArea )
    } );
    
    const SignupSchema = Type.Object( {
        signup: Type.Boolean( {
            checked: false,
            element: "input",
            inputType: "checkbox",
            label: "Add me to the list!",
        } satisfies FormInputCheckbox ),
    
    } );
    
    export const Schema = Type.Composite( [
      UsernameSchema, EmailSchema, PasswordSchema, SignupSchema, CommentSchema
    ] );
      
    ts
    2
  • Generate the Form HTML

        // ~/examples/basic/form.ts
    import {Form} from "cruddy-forms";
    import {Schema} from "~/examples/basic/schema.ts";
    
    export const formHTML = new Form(Schema).getHTML();
      
    ts
  • 3
  • Serve the Form HTML and CSS

    The details of this step will depend on your chosen server-side rendering framework. Include the generated Form HTML from Step 2 in your server response, along with the normform.css file.
  • 4
  • Resulting Form (Try it!)

    Username may not contain spaces
    Use 6 or more characters