Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ Submitting a form in Nextjs 14 with onBlur, server actions, and validation

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Submitting a form in Nextjs 14 with onBlur, server actions, and validation


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Want a straightforward article on submitting a form in Nextjs to a server action using an HTML event onBlur? And with form validation?

Then this is the article for you. I found the documentation on Nextjs.org lacking, so I'm putting this here for you.

This article is suitable for other events, such as onChange. Still, I prefer onBlur; as you know, the user is done typing, and you don't have to mess with debouncing.

The Form

This tutorial has a simple input field within the form asking for a name.

I want the user to save the field without hitting a submit button. So, the form has no buttons; the user types and the code does the rest.

"use client";

import React from "react";
import { useFormState } from "react-dom";
import { saveName } from "@/src/libs/actions/SaveName";

export default function NameForm() {

  const initialState = { message: "", errors: {} };
  const [state, formAction] = useFormState(saveName, initialState);

  return (
    <form action={formAction}>
      {state && state.message && <div>{state.message}</div>}
      <div>
        <label htmlFor="name">
          Enter your name
        </label>
        <div>
          <input
              name="name" 
              id="name"   
              type="text"
              required
              placeholder="Ex. Brandon Sanderson"
              onBlur={async (e) => { 
                const formData = new FormData();
                formData.append("name", e.target.value);
                await formAction(formData); 
              }}
          />
          {state && state.errors?.name &&
            name((error: string) => (
              <p key={error}>
                {error}
              </p>
            ))}
        </div>
      </div>
    </form>
  );
};

Okay, let's break this down. To make our lives easier and provide error messages, we're using the React hook useFormState. As of this writing, this newer feature is only available in a Canary build. But it's been stable for me.

const initialState = { message: "", errors: {} };
const [state, formAction] = useFormState(saveName, initialState);

We first create a state object, which we'll use to handle our validation messages.

We then create our state object and formAction by passing to useFormState a reference to our function (a NextJS server action) and the initial state.

<form action={formAction}>

We use the Nextjs syntax to call our server action in our form. If you don't include this when a user hits enter within a field, it will not call your server action.

<input
  name="name" 
  id="name"   
  type="text"
  required
  placeholder="Ex. Brandon Sanderson"
  onBlur={async (e) => { 
    const formData = new FormData();
    formData.append("name", e.target.value);
    await formAction(formData); 
  }}
/>

The input is standard right up to the onBlur. We cannot call the form's action from onBlur, but we can trigger the same action ourselves. But you must make a FormData object yourself. FormData is just a simple interface; you can create it with a call to new FormData(). We then populate it with an append, which requires a key/value pair. Then, we call our server action created via the hook.

The Server Action

For the server action, we'll include validation since we want to give the user an experience that lets them know if something has gone wrong.

"use server";

import { z } from 'zod';

const NameFormSchema = z.object({
    name: z.string().min(2, { message: 'You must enter at least two characters'}),
});

export type State = {
    errors?: {
        name?: string[];
    };
    message?: string | null;
}

export async function saveWebsite (prevState: State | undefined, formData: FormData) {

    // Validate Inputs
    const validatedFields = WebsiteFormSchema.safeParse({
        name: formData.get('name'),
    });

    // Handle Validation Errors
    if (!validatedFields.success) {
        const state: State = {
            errors: validatedFields.error.flatten().fieldErrors,
            message: 'Oops, I think there\'s a mistake with your inputs.',
        }

        return state;
    }

    // Do your save here...
}

I'm a big fan of Zod, a typescript validation library. You could roll this yourself. But why do life in hard mode?

Let's break this code down

const NameFormSchema = z.object({
    name: z.string().min(2, { message: 'You must enter at least two characters'}),
});

Zod uses a schema format. So first, you need to tell it the schema of the form you'll be using. Each field you're submitting will have an entry. In this case, just one field.

export type State = {
    errors?: {
        name?: string[];
    };
    message?: string | null;
}

This is the type we'll be using for our form state. We must define its type fully because we're populating it and using TypeScript. We use this object to pass back errors. If you look at the form, you can see how it's used, as it's fairly straightforward.

// Validate Inputs
    const validatedFields = WebsiteFormSchema.safeParse({
        name: formData.get('name'),
    });

    // Handle Validation Errors
    if (!validatedFields.success) {
        const state: State = {
            errors: validatedFields.error.flatten().fieldErrors,
            message: 'Oops, I think there\'s a mistake with your inputs.',
        }

        return state;
    }

Validation is also straightforward with Zod. First, we safely parse the fields we want. Then, we check for any errors that were created during the parse. If they exist, we package them up into our state object.

The last step is up to you. Save to a database or call an API. But be sure to capture any errors and use the state object if they occur.

...



๐Ÿ“Œ Submitting a form in Nextjs 14 with onBlur, server actions, and validation


๐Ÿ“ˆ 112.9 Punkte

๐Ÿ“Œ Allowed bypassing CAPTCHA validation when submitting form data


๐Ÿ“ˆ 39.73 Punkte

๐Ÿ“Œ Actions Project - Actions Builder & Actions SDK


๐Ÿ“ˆ 36.26 Punkte

๐Ÿ“Œ Conversational Actions overview - Actions Builder & Actions SDK


๐Ÿ“ˆ 36.26 Punkte

๐Ÿ“Œ What is NextJs?ย  Why Should You Use it in 2023?ย  NextJs Pros and Cons Guide


๐Ÿ“ˆ 35.54 Punkte

๐Ÿ“Œ NextJS examples: 60 popular websites built with NextJS and headless CMS


๐Ÿ“ˆ 35.54 Punkte

๐Ÿ“Œ 3 Exciting Improvements Between NextJS 14 And NextJS 13


๐Ÿ“ˆ 35.54 Punkte

๐Ÿ“Œ Low CVE-2022-2144: Jquery validation for contact form 7 project Jquery validation for contact form 7


๐Ÿ“ˆ 33.92 Punkte

๐Ÿ“Œ Deploy Nextjs app to github-pages with Github Actions


๐Ÿ“ˆ 28.97 Punkte

๐Ÿ“Œ Cgiscript.net csMailto csMailto.cgi form-to/form-from/form-results privilege escalation


๐Ÿ“ˆ 28.41 Punkte

๐Ÿ“Œ Simplifying Form Validation with Zod and React Hook Form


๐Ÿ“ˆ 28.2 Punkte

๐Ÿ“Œ How to create a free email subscription form in NextJS, Netlify and MailerLite


๐Ÿ“ˆ 28.13 Punkte

๐Ÿ“Œ Tutorial: Build a contact form with NextJS and BCMS


๐Ÿ“ˆ 28.13 Punkte

๐Ÿ“Œ Wow! Server Actions are now Stable from Next.js 14! Dramatic changes in React and Next's form


๐Ÿ“ˆ 26.71 Punkte

๐Ÿ“Œ Enhancing UX: Leveraging Nextjs Router Events for Form Manipulation


๐Ÿ“ˆ 26.35 Punkte

๐Ÿ“Œ Intents - Actions Builder & Actions SDK


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Scenes - Actions Builder & Actions SDK


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Creating an Action for the Google Assistant with Actions SDK (Behind the Actions, Ep. 8)


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Gitea is working on a built-in CI/CD tool called Gitea Actions (compatible with GitHub Actions syntax)


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Actions 2.3.0 - Useful actions for Shortcuts.


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Announcing Actions Builder & Actions SDK: New tools optimized for the Google Assistant


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Creating an Action for the Google Assistant with Actions Builder (Behind the Actions, Ep. 7)


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Overview - Actions Builder & Actions SDK


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ actions-hottest๐Ÿš€: GitHub Actions for Commenting on Golang Unit Test Results in Pull Requests


๐Ÿ“ˆ 24.17 Punkte

๐Ÿ“Œ Android Banking Trojan Tricks Victims into Submitting Selfie Holding their ID Card


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ Five tips for submitting to Calls for Papers


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ First time speaker? Don't be afraid of submitting to the VB2018 CFP


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ A checklist for submitting your first Linux kernel patch


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ nVidia is submitting code to Plasma/Wayland to make it run on their drivers


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ Pwn2Own 2019 โ€“ Apple Safari, VirtualBox, VMware Hacked โ€“ Ethical Hackers Earned $240,000 by Submitting Zero-dayโ€™s


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ bingbot Series: Get your content indexed fast by now submitting up to 10,000 URLs per day to Bing


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ WOW! Submitting A Great Mobile Device UI Themes Portfolio


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ Android Banking Trojan Tricks Victims into Submitting Selfie Holding their ID Card


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ Android Banking Trojan Tricks Victims into Submitting Selfie Holding their ID Card


๐Ÿ“ˆ 22.77 Punkte

๐Ÿ“Œ Android Banking Trojan Tricks Victims into Submitting Selfie Holding their ID Card


๐Ÿ“ˆ 22.77 Punkte











matomo