In the previous part we created a route that responded to a HTTP Post request at localhost:8000 . Let’s make use of Forms and validate user input, so we can save it when we will be adding a database to our app.
Forms are simple classes with fields that show what input is accepted by the app. Create an ArticleForm.ts file inside a Forms directory in the app’s root folder with this content:
📁 Forms/ArticleForm.ts
import { Field, Form } from '@Typetron/Forms'
export class ArticleForm extends Form {
@Field()
title: string
@Field()
content: string
}
Here we have a simple class that extends the base Form class from Typetron. The base Form class contains special methods that are used to validate the user input. When creating a form you should always extend the Form class. Inside the class we have two properties annotated with the @Field() decorator telling Typetron what are the form inputs.
We can now use this form in our add from HomeController to capture the user’s input. Let’s just return the data back to the user to see everything works:
📁 Controllers/Http/HomeController.ts
import { ArticleForm } from 'App/Forms/ArticleForm'
@Controller()
export class HomeController {
@Get()
welcome() {
return [
{
title: 'Making a healthy breakfast'
},
{
title: 'Protein rich meal for gym'
}
]
}
@Get(':id')
read(id: number) {
return {
id: 'This is article with ID #' + id,
title: 'Making a healthy breakfast',
content: 'Content of this article here...'
}
}
@Post()
add(form: ArticleForm) {
return form
}
}
You can test this route by making a POST request and send a raw JSON with the form fields like so and you will get that back from the server:
🌐 [POST] /
{
"title": "title",
"content": "some content"
}
Nothing special here. We can also validate the fields in the form by adding rules to them using the @Rules() decorator. Let’s make the title and content required fields with the title needing at least 5 characters:
📁 Forms/ArticleForm.ts
import { Field, Form, Rules } from '@Typetron/Forms'
import { MinLength, Required } from '@Typetron/Validation'
export class ArticleForm extends Form {
@Field()
@Rules(
Required,
MinLength(5)
)
title: string
@Field()
@Rules(
Required
)
content: string
}
You can also create your own validation rules. Now, whenever the client inputs invalid data, he will get an error. Try adding a title with less than 5 characters inside the body of the request as a raw JSON like in the image below input, and you should see an error like this one: