Example: Internationalization

CruddyForms supports i18n.
    1
  • Define the schema using Typebox

        import {Type} from "@sinclair/typebox";
    import type {FormInputText} from "cruddy-forms";
    
    const EmailSchema = Type.Object( {
      email: Type.RegExp(
        /.+@example\.com/i,
          {
            element: "input",
            hint: {"en": "Must end in @example.com",
                   "es": "Debe terminar en @example.com"},
            inputType: "email",
            label: {"en": "Email",
                    "es": "Correo electrónico"},
            placeholder: {"en": "[email protected]",
                          "es": "[email protected]"},
          } satisfies FormInputText,
        ),
    } );
    
    const PASS_MIN = 6;
    const PasswordSchema = Type.Object( {
      password: Type.String( {
        element: "input",
        hint: {"en": `Use ${PASS_MIN} or more characters`,
               "es": `Usa ${PASS_MIN} o más caracteres`},
        inputType: "password",
        label: {"en": "Password",
                "es": "Contraseña"},
        minLength: PASS_MIN,
        placeholder: {"en": "your password",
                      "es": "tu contraseña"},
        } satisfies FormInputText ),
    } );
    
    export const Schema = Type.Composite( [
      EmailSchema, PasswordSchema,
    ] );
      
    ts
  • 2
  • Generate the Form HTML

    Here we create 2 example formss.

        // ~/examples/basic/form.ts
    import {Form} from "cruddy-forms";
    import {Schema} from "~/examples/i18n/schema.ts";
    
    export function formHTML(lang: string, data?: FormData) {
      const buttonLabel = lang === "es" ? "Enviar" : "Submit";
      const form = new Form(Schema, buttonLabel);
      if (data) {
        form.validate(data);
      }
      return form.getHTML(undefined, lang);
    }
      
    ts
    3
  • Serve the Form HTML and CSS

    The details of this step will depend on your chosen server-side rendering framework. Your server response should include the generated Form HTML from Step 2 and the normform.css file.
  • 4
  • Resulting Forms

    Try out the forms to see the messages in English or Español!

    English


    Use 6 or more characters

    Español



    Usa 6 o más caracteres