When trying to submit a HTML form using Next.js Server Actions, the data that goes to the server function is a FormData object.
Working with a traditional text input is pretty straightforward, you can simply get the text string off of the input's value attribute.
Checkboxes can be a bit different, because most backends and database schemas will prefer a boolean value. We'll explore what the checkboxes and radio button groups look like, when being sent as FormData.
Key Takeaways:
Video where I set up the form with Next.js Server Actions: • Next.js Server Actions Inside React C...
0:34 - We use Zod to parse and validate our form data on the server. My database is expecting a boolean value for the checkboxes on our form.
1:30 - Trying to submit the form with our current checkbox setup, our form validation will error because the value of a "checked" checkbox is the string "on" instead of a boolean value.
2:32 - When we uncheck a checkbox and submit it, the value of the checkbox will be null. This is also not a boolean value and will fail the form validation
3:00 - We can add some logic to change our checkbox values to boolean values. If the checkbox is null, then we'll return false, otherwise we'll return true.
4:11 - Radio buttons that share the same "name" will be a button group. You can pull the value of the button group by using formData.get("radio-group-name")
4:40 - Radio buttons that do not have a value, will also return a string "on". This isn't helpful if we need to know which radio button the user has selected.
5:05 - Make sure your radio buttons have the proper "value" so you can distinguish which radio button is actually selected.
6:14 - When a checkbox has a "value" attribute, the formData.get("checkbox-name") will return a type of string with whatever the "value" is. So instead of "on", it will be what you set as the "value"
7:17 - Our logic from before still works, because we check for null instead of a string.
It's also worth noting that you can group checkboxes together as well, by giving all the checkboxes the same name. You'll want to give them all a value too, just like radio button groups.
You can then use `formData.getAll('checkbox_group_name')` and it will give you all the values that have been checked.
Смотрите видео Validate Form Data Checkboxes and Radio Groups онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Code Bushi 05 Сентябрь 2023, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 1,69 раз и оно понравилось 1 людям.