new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · Guides · all subjects

authentication/validation

11 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Client-side validation uses HTML attributes like required and type='email'

Forms can be validated on the client or server. For client-side validation, you can use HTML attributes like required and type='email' for basic validation.

Server-side validation with zod library

For server-side validation, you can use a library like zod to validate form fields. Use schema.safeParse() to validate the form data and return early with validation errors if validation fails.

useActionState hook receives prevState or initialState as first argument

When using useActionState to display validation errors or messages, the Server function signature changes to receive a new prevState or initialState parameter as its first argument. Example signature: export async function createUser(initialState: any, formData: FormData) {}

useActionState returns [state, formAction, pending]

The useActionState hook returns an array with three elements: state (the current state), formAction (the form action to pass to the form), and pending (a boolean indicating if the action is being executed). Use pending to show loading indicators or disable the submit button.

useFormStatus hook returns pending state for loading indicators

The useFormStatus hook returns an object with a pending boolean that can be used to show a loading indicator while the action is being executed. This hook must be used in a separate component nested inside the form. In React 19, it also includes additional keys like data, method, and action.

Zod validation with safeParse in Server Action

Example of server-side form validation using zod: ```tsx 'use server' import { z } from 'zod' const schema = z.object({ email: z.string({ invalid_type_error: 'Invalid Email', }), }) export default async function createUser(formData: FormData) { const validatedFields = schema.safeParse({ email: formData.get('email'), }) if (!validatedFields.success) { return { errors: validatedFields.error.flatten().fieldErrors, } } // Mutate data } ``` This example validates form data and returns field-specific errors on validation failure.

useActionState with Client Component form

Example of using useActionState in a Client Component to display validation errors: ```tsx 'use client' import { useActionState } from 'react' import { createUser } from '@/app/actions' const initialState = { message: '', } export function Signup() { const [state, formAction, pending] = useActionState(createUser, initialState) return ( <form action={formAction}> <label htmlFor="email">Email</label> <input type="text" id="email" name="email" required /> <p aria-live="polite">{state?.message}</p> <button disabled={pending}>Sign up</button> </form> ) } ``` The Server Action receives initialState as first argument, followed by formData.

useFormStatus hook in separate component

Example of using useFormStatus in a separate component for loading state: ```tsx 'use client' import { useFormStatus } from 'react-dom' export function SubmitButton() { const { pending } = useFormStatus() return ( <button disabled={pending} type="submit"> Sign Up </button> ) } ``` Then nest the SubmitButton component inside the form. The hook must be in a child component to access the form context.

Form validation with Zod schema

Use schema validation libraries like Zod or Yup to validate form fields on the server. Example: name must be at least 2 characters long and trimmed; email must be valid and trimmed; password must be at least 8 characters long, contain at least one letter, at least one number, and at least one special character, and be trimmed.

SignupFormSchema with Zod validation rules

import * as z from 'zod' export const SignupFormSchema = z.object({ name: z .string() .min(2, { error: 'Name must be at least 2 characters long.' }) .trim(), email: z.email({ error: 'Please enter a valid email.' }).trim(), password: z .string() .min(8, { error: 'Be at least 8 characters long' }) .regex(/[a-zA-Z]/, { error: 'Contain at least one letter.' }) .regex(/[0-9]/, { error: 'Contain at least one number.' }) .regex(/[^a-zA-Z0-9]/, { error: 'Contain at least one special character.', }) .trim(), })

Return early from Server Action on validation failure

To prevent unnecessary calls to your authentication provider's API or database, return early in the Server Action if any form fields do not match the defined schema. Check validatedFields.success and return errors.error.flatten().fieldErrors if validation fails.

Give your agent this brain