For Developers

Angular 4 Validation: Nested Form and Input Validation

Angular 4 Validation

Forms are a significant part of any web application. It demands sensitive information from the user that is used to log in, build a profile, and more on an application.

So, when we talk about forms in Angular 4, we discuss different forms in Angular and how rules like validators check the information filled by the user. It is done to decide whether the user input will be accepted or rejected without having to check each input separately in the form.

In this article, we will mainly focus on Angular 4 validation, how you can do it, and a recap of the basics.

Forms in Angular 4

There are two forms of Angular 4 namely Template and Nested. Let’s discuss them in details below.

Template-driven forms

It uses the conventional form tag to create forms. Most of the work is done in the template. The form object representation for the tag is automatically interpreted and created by Angular.

You can add controls to the form using the NGModel tag. Using the NGControlGroup module, you can even group multiple controls.

To validate the form fields, use basic HTML validations. However, if you wish to carry out custom validations, ‌make use of the directives.

For a brief understanding, Let’s create a simple login form of inputs for email ID, password, and the submit button in the form.

Step 1: Import @angular/core which is done in app.module.ts to FormsModule as follows.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';

@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      HttpModule,
      FormsModule,
      RouterModule.forRoot([
         {path: 'new-cmp',component: NewCmpComponent}
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})

export class AppModule { }

Code source

Step 2: Next, we create a form in the app.component.html file as follows.

<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
<input type = "text" name = "emailid" placeholder = "emailid" ngModel>
<br/>
<input type = "password" name = "passwd" placeholder = "passwd" ngModel>
<br/>
<input type = "submit" value = "submit">
</form>

With this, a simple form will be created with the assigned type, name, and placeholder to it. Now to create the model form controls, we need to add the ngModel directive and the name attribute. It will also help Angular to access the data in the forms.

Tip: If you wish to view the email ID and password, add the ngModel to that tag.

Step 3: Now to fetch the values entered in the form, we will create the function in the app.component.ts as follows.

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   title = 'Angular 4 Project!';
   todaydate;
   componentproperty;
   constructor(private myservice: MyserviceService) { }
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
   }
   onClickSubmit(data) {
      alert("Entered Email id : " + data.emailid);
   }
}

With the onClickSubmit function defined in the above app.component.ts file, the control will come to the above function when you click on the form submit button. In the end, the following form that you created above will be displayed as follows.

Login form.webp

Nested forms

An Angular nested form is a form within a form or, say, the manipulation or creation of a model is different from the parent form model. It allows you to create an array of objects within a single field which sums up to an array of these fields. This way, you can manage large form groups and still divide them into small groups for a better understanding.

For instance: Let’s create a profile for a user that has multiple addresses along with multiple phone numbers inside each address.

{
"name": 'abc',
"addressess": [{
"street": 'sanjay nagar',
"phone number": [
{
number1: 984561
},
{
number2: 1589625674
}]
},
{
"street": 'nehru nagar',
"phone number": [
{
number1:7412561234
},
{
number2:1578969876
}]
}]
}

Code source

Now that you are acquainted with the forms and how you can create them in Angular, let’s address the elephant in the room, i.e. the validators.

Validators

Validators are rules that are mandatory to be followed by the input control. In case, the input control cannot match the rules, it is termed invalid input.

Angular includes a small set of pre-built validators that are like the ones we define via standard HTML5 attributes like pattern, maxlength, minlength, and required. You can access these from the validators module. These validators are applied by defining the FormControls in our model or by simply adding attributes to the templates.

Let’s consider an Angular 4 form validation example with a sign-up form in which all the fields are required. However, to dictate a stronger password, we will specify complex validators. So, if we are to apply validators, here’s how we can do it.

import { FormGroup, FormControl, Validators } from '@angular/forms';
.
.
.
class ModelFormComponent implements OnInit {
  myform: FormGroup;

  ngOnInit() {
    myform = new FormGroup({
        name: new FormGroup({
            firstName: new FormControl('', Validators.required), (1)
            lastName: new FormControl('', Validators.required),
        }),
        email: new FormControl('', [ (2)
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*") (3)
        ]),
        password: new FormControl('', [
            Validators.minLength(8), (4)
            Validators.required
        ]),
        language: new FormControl() (5)
    });
  }
}

Code source

In the above code, we have added a single required validator to mark this control as mandatory. To check whether the email contains @ character, we have specified a patterned validator. Again, to ensure that the password is a minimum of eight characters, the minlength validator has also been included in the code. This way you can provide validators from the available set in the validators module.

Validation expressions

Sometimes writing validation expressions quickly can become cumbersome to use in the templates, in the case of angular nested forms.

For instance: We know that firstname and lastname in FormControls will exist under the name FormGroup, instead of following a lengthy syntax, we can use the syntax below to make it less cumbersome.

<div class="form-group"
       [ngClass]="{
        'has-danger': myform.controls.name.controls.firstName.invalid&&myform.controls.name.controls.firstName.dirty,
        'has-success': myform.controls.name.controls.firstName.valid&&myform.controls.name.controls.firstName.dirty
}">

Validation messages

While styling a form, it is necessary to show error messages to the user. This will inform the user in case their input is invalid and also display how they can resolve them. Bootstrap comes in handy when we need to show visual feedback when the form controls are invalid.

You can find some classes and markup for form controls that can be used for error messages. To understand it in brief, here’s how you can add them to the password form control.

<div class="form-group">
  <label>Password</label>
  <input type="password"
         class="form-control"
         formControlName="password">
  <div class="form-control-feedback" (1)
       *ngIf="password.invalid && password.dirty"> (2)
    Field is invalid
  </div>
</div>

With the above code, a red message saying “Field is invalid” will be displayed in the password field, including a messy and invalid message.

The above example shows a generic validation error message. But, this field is to be linked with two validators that are “required” and “minlength”. So, we would need to show a separate validation error message for each of the validators with the help of another property on our form control called errors. It is an object that has one entry per validator. You can use it as follows.

<div class="form-control-feedback" *ngIf="password.errors && (password.dirty ||
 password.touched)">
  <p *ngIf="password.errors.required">Password is required</p>
  <p *ngIf="password.errors.minlength">Password must be 8 characters long</p>
</div>

Since the value includes useful information for the user like minlenth, it gives us the info about the actualLength and requiredLength properties.

{
  "minlength": {
    "requiredLength": 8,
    "actualLength": 1
  }
}

We can wisely use it in the validation error messages to direct the user on how they can resolve the issue they are facing.

<div class="form-control-feedback"
     *ngIf="password.errors && (password.dirty || password.touched)">
  <p *ngIf="password.errors.required">Password is required</p>
  <p *ngIf="password.errors.minlength">Password must be 8 characters long, we need another
 {{password.errors.minlength.requiredLength - password.errors.minlength.actualLength}} characters </p>
</div>

With this, the validator will show the following error message:

  • Password is required when no input is entered.

  • Password must be 8 characters long.

Conclusion

Angular 4 validation checks the validity of each field included in the form. They improve overall data quality to ensure completeness and accuracy by validating the user input. This article has informed you on how to validate user input along with displaying validation messages.

Author

  • Author

    Srishti Chaudhary

    Srishti is a competent content writer and marketer with expertise in niches like cloud tech, big data, web development, and digital marketing. She looks forward to grow her tech knowledge and skills.

Frequently Asked Questions

Instant validation comes as the best choice for input validation, as it aligns well with the positioning of the right-hand side of the input. It simplifies the tedious process of form inputs.

Angular 4 Validation is referred to when a system verifies its stated functional intent with that of the input by the user. On the contrary, calibration is referred to as the accuracy of the measurement of an instrument.

Add similar validation attributes as you do in native HTML form validation to add validation in template-driven forms. Angular will match these attributes with the help of directives to the validator functions in the framework.

View more FAQs
Press

Press

What's up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work.
Checkout our blog here.
Contact

Contact

Have any questions?
We'd love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.

Hire Developers