Example: Testing Server-side Validation
In this example we set novalidate: true to disable client-side validation, in order to demonstrate server-side validation. This is only for demo purposes. It is recommended to always enable both client-side and server-side validation on your website.
-
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
1
-
Generate the Form HTML
Notice the novalidate attribute passed to the Form constructor. This disables client-side validation, so that we can test submitting unvalidated data to the server.// ~/examples/servertest/form.ts import {Form} from "cruddy-forms"; import {Schema} from "~/examples/basic/schema.ts"; export function getHTML(data?: FormData) { const form = new Form(Schema, "Test Server Validation", {novalidate: true, action: "#form"}); if (data) { const result = form.validate(data); if (result.valid) { form.setErrorMessage("Valid!", []); } } return form.getHTML(); }
ts -
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. -
Resulting Form (Try it!)
Since client-side validation is disabled in this example, you'll be able to submit the form even if the data is invalid. You'll see some basic error messages from the server displayed at the bottom of the form.
2
3
4