In this article, we will teach you how to implement validation forms in Ionic 3 using Angular. We will teach you how to create the best form validations by restoring optimum user experience of your app.

We will show you a lot of examples of different types of validations and how you can implement them in your own forms but before all of that, let’s get into some pre-requisites.

Why use forms?

Forms are the basic building block of any business application or web apps. The form is the first thing a consumer will use when they interact with your business online for the first time. Forms can be used for many things like knowing the interests of the customer, or taking a review of your service or just for information about the customer like their name and contact so that you can reach them later to promote your services. We think you have an idea now that how important forms are to your business and why they should be well designed and implemented.

Designing good forms require creative skills as well as the required framework that supports two-way data binding, validation, change tracking, and error handling. All of these things are supported by Angular which we will be using in this guide to implement form examples.

Angular Forms

Let’s understand a bit about Angular Forms first before we get into the more technical part. So there are two kinds of Angular Forms which can be used. The first one is Angular Reactive Form and the second one is Template Driven Form. We will be using the reactive form in this article but let’s dig into these briefly for knowledge sake.

Angular Reactive forms

The reactive Angular forms basically help in reactive programming that implements explicit data management. The data flows between non-UI data models, generally from a server, and an interface based form model that is showcased on the screen using HTML. Reactive forms are used to implement reactive patterns, testings and validations. We completely avoid using models like ngModel, NgForm, required and use the inbuilt APIs present into Angular Reactive library module ReactiveFormsModule.

Angular Template driven forms

Template driven forms are completely different compared to the Reactive forms. HTML tags such as <input> or <select> are used in the component template and then bound to data model properties using the ngModel directive.

The other difference is that when using template driven forms, form control objects are automatically created by Angular directives like ngModel by using data binding information provided by you. Some other directives used in template driven forms are required and minlength; required makes a field mandatory to be filled by the user and minlength sets the minimum character limit.

So now that we have discussed in brief the two technique of Angular to implement forms, we can begin with the tutorial. We will be using the reactive approach in this guide to implement forms in Ionic 3.

Angular form Basics

Below are some of the basic concepts in the reactive approach.

Form Control: It is used to keep track of the value and validity status of an Angular Form Control. It is similar to HTML form tags like <input> and <select>.
Let’s see an example of Form Control implementation below:

ts file:

this.name =newFormControl('Harvij Writings',Validators.required)

html file:

<ion-input type="text" formControlName="name of writer"></ion-input>

The Validators.required in the ts file indicates that the field must not be empty whereas the html file defines what the field is for and what type of data it should have.

FormGroup: FormGroup is used to track the value and validation state of a FormBuilder in an instance of a group. It specializes each child FormControl values into a single object and uses the form control name as its key. Calculation of its status is done by reducing the status of all the children. For an example, if any control or object is invalid in a group then the whole group’s validation becomes invalid. See the below example for further clarity.

this.user=newFormGroup({
company name:newFormControl('Harvij Writings',Validators.required),
email:newFormControl('harvijwritings@gmail.com',Validators.required)
});

This will ensure that even if one of the fields remain empty then the form cannot be processed further.

FormBuilder: It is a supporting class that is used to create FormControl, FormGroup, and FormArray. It is basically an approach to improve syntax redundancy from the code.

this.validations_form=this.formBuilder.group({
name:newFormControl('',Validators.required),
email:newFormControl('',Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
]))
});

All of these directives are a feature of the @angular/forms library and should be imported in the form by using the following syntax.

import{ Validators, FormBuilder, FormGroup, FormControl }from'@angular/forms';

The perfect Validation Timing

The validation timing of your form matters a lot for the user experience. Let’s understand this with a situation, suppose you have filled a very long form and when you click on submit, it gives you all sorts of validation errors then you may not even bother to fill the form again.

So instead of doing the validation only at the end, it is much better to try these two approaches:

  • Real Time Validation: It means to validate the field as the user types, to check for validation at every key pressed. This is the default mode of Angular Validators.
  • On Blur: On blur is kind of a partially real-time validation. Instead of validating on every key press, validation check occurs as soon as the users enter the next field.

Ionic Forms and Validations

In reactive forms, we don’t add validators through attributes like we do in template driven validation, we add validators directly in the form control model of angular component class. Angular calls these functions atruntime according to the method of validation.

You can create custom validators as well as take advantage of the inbuilt angular validators like the required. Built-in validators are vanilla validators that are provided with the Angular libraries. However, it is recommended to use custom validators as they will match the use case of your application more accurately than those from the built-in library.

Now let’s see a big example form and use a different kind of validations in it.

Name

  • Required

Last Name

  • Required

Email

  • Valid Mail
  • Required

Terms and policies checkbox

  • Must be accepted

Let’s now implement this one by one using appropriate validators.

Basic Validators

  • Required: It states that the field must not remain empty and a value is necessary for it. It also ensures that the value entered must be of the field’s type; eg: numbers only in phone number field.
  • Minlength: validates a field to have a minimum number of characters.
  • Maxlength: validates a field to have a maximum limit on the number of characters entered.
  • Pattern: ensures that the entered value matches a regex. You will understand it better in the below example.
  • Email: ensures that the entered value is an email address.
  • Compose: it is used to employ a combination of multiple validators on the same field.

Let’s use these validators for our form now. Let’s start with the following fields:

  • Name: Required
  • Last name: Required
  • Email: valid format and required
  • Terms and policy: must be accepted

Let’s create a form control for each of them first with the respected validations.

name:newFormControl('',Validators.required),
lastname:newFormControl('',Validators.required),
email:newFormControl('',Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
terms:newFormControl(true,Validators.pattern('true'))

As you can see, pattern validator is used with email to ensure the correct format and compose is used to apply two validations on the field. Whereas name and last name have the simple required validation applied.

Custom Error Message

Defining custom error messages is very important for better understandability of the user. Now we will learn how to show different error messages for different validators we have indicated above.

validation_messages={
'username':[
{ type:'required', message:'You must enter a username.'},
{ type:'minlength', message:'Minimum 5 characters are required for username.'},
{ type:'maxlength', message:'You can enter a username of maximum 30 characters.'},
{ type:'pattern', message:'Username should be composed of numbers and letters.'},
{ type:'validUsername', message:'A user with the selected username already exists.'}
],
'name':[
{ type:'required', message:'Name is required.'}
],

....//more messages
}

And now we have to iterate this list into our HTML file to show the right message which is achieved below:

<ion-item>
<ion-label floating color="primary">Username</ion-label>
<ion-input type="text" formControlName="username" class="form-control"></ion-input>
</ion-item>
<div class="validation-errors">
<ng-container *ngFor="let validation of validation_messages.username" >
<div class="error-message" *ngIf="validations_form.get('username').hasError(validation.type) && (validations_form.get('username').dirty || validations_form.get('username').touched)">
{{ validation.message }}
</div>
</ng-container>
</div>

Some Suggestions

When you create your form, make sure that you keep it as user-friendly as you can because the users will always be attracted towards services which have a clearer and simpler interface and the forms play a major part in this segment. The more user intuitive your forms are, the more likely it is to get a good response from the users.

If you are learning angular just to start your own service for businesses, we recommend you to practice as much as you can and try different variations of the validators and other features of this language.

Thanks for reading.

We hope we were able to help you with validators.

LEAVE A REPLY

Please enter your comment!
Please enter your name here