Validate Form Data Checkboxes and Radio Groups
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: https://www.youtube.com/watch?v=I7VSqBgja3c
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.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Validate Form Data Checkboxes and Radio Groups», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.