@@ -313,6 +313,88 @@ export default function Page() {
313313}
314314` ` `
315315
316+ For more complex forms, you can use a schema library like [Valibot](https://valibot.dev/) to define your validation rules:
317+
318+ ` ` ` tsx tab title= " TypeScript" {4 } {6 - 11 } {14 - 19 }
319+ // src/routes/index.tsx
320+ import { Show } from " solid-js" ;
321+ import { action , useSubmission } from " @solidjs/router" ;
322+ import * as v from " valibot" ;
323+
324+ const PostSchema = v .object ({
325+ title: v .pipe (
326+ v .string (),
327+ v .minLength (2 , " Title must be at least 2 characters" )
328+ ),
329+ });
330+
331+ const addPost = action (async (formData : FormData ) => {
332+ const result = v .safeParse (PostSchema, {
333+ title: formData .get (" title" ),
334+ });
335+ if (! result .success ) {
336+ return { error: result .issues [0 ].message };
337+ }
338+ await fetch (" https://my-api.com/posts" , {
339+ method: " POST" ,
340+ body: JSON .stringify (result .output ),
341+ });
342+ }, " addPost" );
343+
344+ export default function Page () {
345+ const submission = useSubmission (addPost);
346+ return (
347+ < form action= {addPost} method= " post" >
348+ < input name= " title" / >
349+ < Show when= {submission .result ? .error }>
350+ < p> {submission .result ? .error }< / p>
351+ < / Show>
352+ < button> Add Post< / button>
353+ < / form>
354+ );
355+ }
356+ ` ` `
357+
358+ ` ` ` jsx tab title= " JavaScript" {4 } {6 - 11 } {14 - 19 }
359+ // src/routes/index.jsx
360+ import { Show } from " solid-js" ;
361+ import { action , useSubmission } from " @solidjs/router" ;
362+ import * as v from " valibot" ;
363+
364+ const PostSchema = v .object ({
365+ title: v .pipe (
366+ v .string (),
367+ v .minLength (2 , " Title must be at least 2 characters" )
368+ ),
369+ });
370+
371+ const addPost = action (async (formData ) => {
372+ const result = v .safeParse (PostSchema, {
373+ title: formData .get (" title" ),
374+ });
375+ if (! result .success ) {
376+ return { error: result .issues [0 ].message };
377+ }
378+ await fetch (" https://my-api.com/posts" , {
379+ method: " POST" ,
380+ body: JSON .stringify (result .output ),
381+ });
382+ }, " addPost" );
383+
384+ export default function Page () {
385+ const submission = useSubmission (addPost);
386+ return (
387+ < form action= {addPost} method= " post" >
388+ < input name= " title" / >
389+ < Show when= {submission .result ? .error }>
390+ < p> {submission .result ? .error }< / p>
391+ < / Show>
392+ < button> Add Post< / button>
393+ < / form>
394+ );
395+ }
396+ ` ` `
397+
316398## Showing optimistic UI
317399
318400To update the UI before the server responds:
0 commit comments