Reader small image

You're reading from  Mastering Blazor WebAssembly

Product typeBook
Published inAug 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235103
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Mozaffar
Ahmad Mozaffar
author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar

Right arrow

Capturing User Input with Forms and Validation

So far, we have learned how to develop components, but all of the components we have built are for displaying data and rendering the UI of the app. Now, we will learn about existing components and develop new ones to build forms that allow the user to insert data and validate it. In almost every app you build, you will need to ask your users for some input. Whether you are building a social network platform, a point-of-sale app, a chat app, or even a simple blog, user input is always required, either to submit a new post, insert a new sales record, or submit a comment on a blog post.

In this chapter, we will cover everything you need to know to build simple and advanced forms. We will discover how Blazor deals with forms, in addition to the different input components that are built into Blazor. After building a form, we will deep-dive into the different methods of validating the data provided by the user. Finally, we will see an example...

Technical requirements

The code used throughout this chapter is available in the book’s GitHub repository at https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_05/ChapterContent.

The modified and final version, which contains a real-world implementation of forms and validation, is in the same repository in the Final folder: https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_05/Final.

Understanding forms in Blazor

Forms are basically sets of one or more input controls, such as text, numbers, and dates. Data collected through forms is submitted at once to achieve a task such as adding a new product to the stock. Let’s look at an example of a social network platform: users should be able to add new posts or edit existing posts. In addition to that, users must be able to comment on other users’ posts. To achieve all of that, you need a mechanism for collecting post interaction (insertion or deletion) data through the UI. This data collection is made possible through forms.

Another example where forms are useful is a job-seeking platform where companies publish their vacancies and job seekers search and apply for them. A form is needed so that HR users at the companies can submit their job positions with information such as descriptions, availability, conditions, and salaries. On the other hand, the user needs a form to pick a job to apply for, upload...

Discovering Blazor’s built-in input components

We have a developed our first form using HTML input elements, and everything went well, but Blazor has its own set of input components that give us better control and more features. In this section, we will discover those components and upgrade our form to be more efficient.

The built-in input components automatically update the CSS class of the input based on the validation state, so we can easily apply styles for the invalid elements. We will have a closer look at that in the next section.

So, let’s deep-dive into our components.

InputText

The first input component to visit is InputText. This gets rendered into the <input type="text" /> HTML element. Going back to our form from the previous section, we will upgrade the input of Title and the input of Author to use the InputText component, as shown here:

...<div class="form-group mt-1">
      &...

Validating form input

Validating the input means checking whether the data entered in the input components satisfies a set of predefined rules. This process has many benefits, such as ensuring the right format of data is being submitted, guiding the users to put the correct values in the correct fields, and saving resources by preventing specific logic from happening if the data is not valid. It also prevents some malicious activity that could arise from certain input.

Let’s take a login page as an example. On the login page, you ask the user to enter an email address and password, then you check whether they are valid. The first thing to check is whether the email address is a valid email address and that it’s not any random text value. The same applies to the password; you have rules such as the minimum number of characters and different types of characters required.

By defining these rules for the form, you ensure that you will receive the data in the correct...

Developing a custom input component

Blazor contains a class called InputBase<T>, which is the base class for all the input components that we have seen so far. The great thing about this class is that we can use it to develop our own input component with the same specifications as the built-in ones.

InputBase<T> has a method called TryParseValueFromString, which is the main method that we need to override, and this is where we can locate the logic that processes the string of the input and translates it into something more meaningful. There is also a property called CurrentValue, which we can use to bind our insider input to.

Blazor already has an InputDate component that gets rendered to an input tag of the date type in HTML, so in the next example, we are going to create a custom component called InputTime, which will be translated to the input tag of the time type. We can bind a TimeOnly value to it. Let’s get started:

  1. Within the BooksStore.Blazor...

Summary

In this chapter, we have covered some important topics in client-side software development: forms, data submission, and validation. We went over the basic definitions of forms and introduced the EditForm component in Blazor. Then, we reviewed the built-in input components in Blazor. After that, we covered the concept of validation and the DataAnnotationsValidator, ValidationSummary, and ValidationMessage components. Finally, we showed an example of how to develop our own custom input component. With these topics covered, you should have learned the following:

  • Why we need forms and how they work
  • How to develop a basic form using the EditForm component in Blazor
  • How to use the built-in input components available in Blazor
  • How to validate the input of the user using data annotation validators and view the result in the UI
  • How to develop a custom input component for advanced cases where the built-in components aren’t suitable

In the next chapter...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blazor WebAssembly
Published in: Aug 2023Publisher: PacktISBN-13: 9781803235103
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar