Angular12 Form Validation, Authentication and Authorization

When a user is not adequately led or instructed, he or she is more likely to submit inaccurate or incomplete information. As a result, we must check user input to ensure the information's completeness and correctness.

In this chapter, we'll look at how to validate user information from forms in both template-driven and reactive forms.

How to validate user Input in Template Driven Forms

This type of angular form uses the directives to match the validator functions attributes in the framework. This means that angular will run the validation every time the form control changes to generate invalid inputs, errors, or null results.

 

<input type="text" id="name" name="name" class="form-control"
      required minlength="4" appForbiddenName="bob"
      [(ngModel)]="hero.name" #name="ngModel">
<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert">
  <div *ngIf="name.errors?.required">
    Name is required.
  </div>
  <div *ngIf="name.errors?.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors?.forbiddenName">
    Name cannot be Bob.
  </div>
</div>

 

How to validate user Input in Template Driven Forms

In this type of angular form, we use the component classes to validate the user input. This means that you should directly add the validator's functions to the form control in the component class instead of adding to the template attributes.

The validator functions can either be asynchronous or synchronous

  • Asynchronous-These functions take control immediately, and they return the  set of errors  or the null results

  • Synchronous- these functions take control and return an observable where the validation errors are emitted later.

During the form validation, you can either decide to use the already built-in validators or write your own validators. In this tutorial, let's look at how you can validate the user input using the built-in and custom validators.

  1. Built-in Validators

Instead of developing your own validator methods, angular provides a built-in validator that you can quickly integrate into your code, saving you time.

  • The minlength, maxlength, and required functions are among the built-in validators.

  •  The minlength method verifies whether the user-submitted more data than the actual value

  • The maxvalue function guarantees that the user did not enter additional characters, and the needed function ensures that the user did not submit null data.

Example of built-in validators

 

ngOnInit(): void {
  this.heroForm = new FormGroup({
    name: new FormControl(this.hero.name, [
      Validators.required,
      Validators.minLength(4),
      forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
    ]),
    alterEgo: new FormControl(this.hero.alterEgo),
    power: new FormControl(this.hero.power, Validators.required)
  });
}
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm.get('power'); }

 

 

Custom Form validators in Angular12

The built-in validators are simple and perform admirably; nevertheless, they may not show the message you need. You may wish to display customized error messages that teach users further or assist the user in understanding how the information should be input.

Angular allows you to construct validators that are specific to your website's situation. Let's have a look at how to include a custom validator in both reactive and template-driven forms.

Adding Custom Validators in Reactive forms

In the case of reactive forms, insert your own validator straight into your FormControl, as seen below

this.heroForm = new FormGroup({
  name: new FormControl(this.hero.name, [
    Validators.required,
    Validators.minLength(4),
    forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
  ]),
  alterEgo: new FormControl(this.hero.alterEgo),
  power: new FormControl(this.hero.power, Validators.required)
});

 

Customizing Validators for Template-Driven Forms

The validator function should be included in the template directive in the case of template-driven forms

@Directive({
selector: "[appForbiddenName]",
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
@Input("appForbiddenName") forbiddenName = "";

validate(control: AbstractControl): ValidationErrors | null {
return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, "i"))(control)
: null;
}}

 

  1. Authentication and Authorization

 

In this era, there are many security risks associated with unauthorized access to sensitive information. When user information is exposed to a third party, severe financial loss and data distortion can occur.

To secure user information from unauthorized access, user authentication and authorization is used, in which the user must verify that he is the rightful owner of the information.

We'll look at how angular authentication and authorization are used to manage user access to private information in this part. We'll go through how to create a user login form that authenticates and authorizes users.

Authentication

Authentication often includes a user entering a secret login username or email address and a password or pin to get access to various sites or services. In Angular 12, authentication is essentially dependent on saving the user's state. This looks to be a violation of HTTP's fundamental characteristic of being a stateless protocol.

A JSON Web Token (JWT) is introduced to address this issue. The JWT protocol allows your application to connect with the backend server that generates the tokens. In this chapter, we will look at how JWT authentication may be used to authenticate a user.

How JWT Authentication Works

Let's have a look at how JWT authentication works in Angular apps.

If a user wants to access a certain service, the server must first validate the credentials supplied by the user, and if they match, the server must next encode the key user information provided into the JSON string.

The text is then turned into a secret key, the JSON web token, and sent back to authenticate the user. The user is deemed to be authenticated when the server confirms the token with the correct key; nevertheless, this procedure has numerous downsides because it is easy to allow fraud, especially if the server already knows the key.

 

The Functionalities of the JWT Authentication

  • It enables you to register using angular forms, both reactive and template.

  • You can access the application after successfully registering.

  • If you enter incorrect login credentials, the backend creates a token sent to the client.

  • The created token is saved to local storage.

  • After successfully login in, you may set the token on the header.

  • Allows you to configure the auth guard to protect all private routes depending on the users that have been granted access.

The JWT Authentication process

Let's go through the angular JWT authentication procedure step by step.

Step 1:  Begin a new Angular 12 project.

To begin a new project, type "ng new angularappli" into your CLI. Then, in our project, we enable app routing and CSS.

Step 2: Run the command ng serve-o to have your application run automatically in your browser.

Step 3: Create a node. js-powered server now. As our backend server in this tutorial, we will utilize the Node.js server. We'll need to put this server under a subdirectory called auth. In this folder, start the package. JSON using the npm init –y command. Our package will install all of the server-side dependencies that this application will require to run our server. Now, execute the following command to install the nodemon server under our project's dev-dependency: nodemon –save-dev npm install

Step 4: Create a new file server to connect our application to the server we just constructed. js and copy and paste the following code

// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.get('/', function (req, res) {
  res.send('hello');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server is running on PORT ${PORT}`);
});

 

That's all; you've successfully deployed the node. server.js

Step 5:  Now, use the command mongod to install the MongoDB database on the node. JS stands for JavaScript.

Conclusion

We learned how to verify angular forms and ensure that the user provides proper and accurate information in this chapter. We also spoke about the significance of user authentication and authorization in online apps and how to get started with the JWT authentication process