Guide chapters
Forms
Cot has form processing capabilities that allows you to create forms and handle form submissions with ease. Processing forms is as easy as creating a Rust structure, deriving a trait, and then using one function to process the form using the request data. Cot will automatically validate the form data and handle any errors that occur.
Form trait
The core of the form processing lies in the Form
trait inside the cot::form
module. This trait is used to define the form and the fields that are part of the form. Below is an example of how you can define a form:
use ;
And here is how you can process the form inside a request handler:
use ;
use ;
use ;
async
Forms in templates
Before this is really usable, we need to define the form in the HTML template. Thankfully, Cot provides you with a way to implement this easily, too—it can automatically generate the HTML for the form based on the form definition.
There are several ways how can you use the forms in your templates. The easiest one is to use the form directly in the template:
Submit
This is especially useful for prototyping new forms, as it doesn’t allow you to customize the rendering of your form. If you need a bit more control, you can use the form.fields()
method to render the fields individually:
Submit
It is recommended to reuse the template code for rendering the form fields using {% include %}
to make it easy to achieve a consistent look and feel across your application.
Field validation
Cot provides several ways to validate form data:
Built-in validation
Custom validation
You can implement custom validation by handling the validation result:
async
Summary
In this you learned how to handle forms and validate form data in Cot applications. Remember:
- Always validate form data server-side
- Provide clear error messages
- Use appropriate field types
- Consider user experience in form layout
- Handle both GET and POST requests appropriately
In the next chapter, we’ll explore database models and how can you use them to persist data in your services.