Next.js Discord

Discord Forum

How to validate data before calling server action

Answered
Standard Chinchilla posted this in #help-forum
Open in Discord
Standard ChinchillaOP
I've the singup page and I'm want to use server action to post the data to the db. All works fine just I want to validate the data before making call to server action.
I've managed to do this using onSubmit but somehow can't figure how to do this using server action cause when the submit button is clicked it straight away calls the action without checking it on client side.

Sign Up form
const SignUpForm = () => {
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
    },
  });

  const onSubmit = (values: z.infer<typeof FormSchema>) => {
    console.log(values);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full">
        // ui
    </Form>
  );
};

Server Action
const FormSchema = z.object({
  name: z.string().min(1, "name is required").max(100),
  email: z.string().min(1, "Email is required").email("Invalid email"),
  password: z
    .string()
    .min(1, "Password is required")
    .min(8, "Password must have than 8 characters"),
});

export async function createUser(formData: FormData) {
  const validatedFields = FormSchema.safeParse({
    name: formData.get("name"),
    email: formData.get("email"),
    password: formData.get("password"),
  });
  // check if the form data is passes type check
  if (!validatedFields.success) {
    return {
      message: "Missing Fields. Failed to Create User.",
    };
  }

  const { name, email, password } = validatedFields.data;

  try {
   // logic
    return {
      message: "User is registered successfully",
    };
  } catch (error) {
    return {
      message: "Database Error: Failed to Create User.",
    };
  }
}
Answered by Arinji
Well, if you want to validate both on the client and server, action won't work, you need to call the onSubmit and then validate there and then finally normally call the server action as a function
View full answer

24 Replies

Well, if you want to validate both on the client and server, action won't work, you need to call the onSubmit and then validate there and then finally normally call the server action as a function
Answer
You won't get stuff like react form status and stuff, but you can validate on the client
Standard ChinchillaOP
okay, so you mean I call createUser(server action) as a function within onSubmit
Yee
Await it as well
Standard ChinchillaOP
I thought it's not conventional
Alot of the new forms stuff isn't really conventional imo
Standard ChinchillaOP
also should I go for server action or create an api route to post the data
what's your thought
Well, I usually try to keep everything as server actions
Standard ChinchillaOP
cause it's almost difficult to get resources on it
Easier to use and type safe as well... You would make an api route if you wanna use it everywhere
Like you made the api route which you hit from a mobile app
Or a different website
It's public to use
You use a server action if it's only for within site
Made sense?
Standard ChinchillaOP
okay, so I just want to sign up that to within site so I should go for server action
Thanks
Yeps :)
Also mark a solution :)
Original message was deleted
Boops
Standard ChinchillaOP
is this you're saying?
Yup