14.3 Forms

In web development, the following workflow will probably look quite familiar:

Open a web page showing a form

Users fill out and submit the form

If a user submits some invalid information or has neglected to fill out a required field, the form will be returned to the user (along with the filled in data) with some descriptive information about the problem.

Users re-fill the invalid fields and continue attempting to submit the form until it's accepted

At the receiving end, the script must:

Check the user submitted form data.

Verify whether the data is the correct type and of the appropriate standard. For example, if a username is submitted, it must verify that it contains only valid characters. Other examples would be checking for minimum and maximum lengths, username uniqueness, and so on.

Filtering data and cleaning up unsafe characters to guarantee that our application only processes data which is safe.

If necessary, pre-format the data (or data gaps need to be cleared through the HTML coding and so on.)

Prepare the data for insertion into the database

Although the procedure is not very complex, it usually requires a lot of boilerplate. In addition, web applications often use a variety of different control structures to display error messages on returned pages. Implementing form validation is a simple but boring task.

Forms and validation

For developers, the general development process can be quite complex, but it's mostly repetitive work. Suppose a scenario arises where you suddenly need to add a form to your project, causing you to rewrite all of the local code tied in with the form. We know that structs are a very commonly used data structure in Go, and Beego uses them to its advantage for processing form information.

First, we define a struct with fields corresponding to the fields in our form element. We can use struct tags which map to the form element, as shown below:

When developing Web applications, first define a struct that matches a field to a corresponding form element, defined by using a struct tag corresponding to the element information and authentication information, as shown below:

For developers, the general development process is very complex, and mostly consists of repeating the same work process. Assuming a scenario for a project whereby a need arises to add data to a form, then the local code of the entire process needs to be modified. We know in Go a struct is a common data structure, so beego uses a form struct to process form information.

First define a struct with fields corresponding to our form element, using struct tags to define the corresponding form element and authentication information, like so:

Above, we've defined the entire first step of displaying a form mapped to a struct. The next step is for users to fill in their information and submit the form, after which the server will receive the data and verify it. Finally, the record will be inserted into the database.