Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: TypeScript Versions In Angular Validation In Angular Reactive Form

clock March 17, 2023 08:06 by author Peter

Angular Reactive forms are an essential part of building modern web applications. These forms allow for a more streamlined approach to managing data input and validation, and they are highly customizable. In this blog post, we will explore how to create an Angular Reactive form with display validation.

Prerequisites
You should have a basic understanding of Angular and Reactive Forms. If you're unfamiliar with these topics, you can check out the official Angular documentation at the portal.

The source code can be downloaded from GitHub

I have used the below tools to prepare this tutorial.
    Angular CLI - 15.1.6
    Node: 18.14.0
    NPM – 9.3.1
    Visual Studio Code

To get started, let's assume we have a simple form that collects basic user information like name, email, and phone number. We'll create a FormGroup in our component to hold our form controls and validators:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, AbstractControl } from '@angular/forms';

@Component({
    selector: 'app-user-form',
    templateUrl: './userform.component.html',
    styleUrls: ['./userform.component.scss']
})
export class UserformComponent implements OnInit {
    userform: FormGroup = new FormGroup({
        name: new FormControl(''),
        email: new FormControl(''),
        phone: new FormControl('')
    });
    submitted = false;
    constructor(private fb: FormBuilder) {}
    ngOnInit(): void {
        this.userform = this.fb.group({
            name: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            phone: ['', [Validators.required, Validators.minLength(10)]]
        });
    }
    get f(): {
        [key: string]: AbstractControl
    } {
        return this.userform.controls;
    }
    onSubmit(): void {
        this.submitted = true;
        if (this.userform.invalid) {
            return;
        }
        console.log(JSON.stringify(this.userform.value, null, 2));
    }
}

We're using the FormBuilder service to create our form controls and validators. The name control is required, the email control is required and must be a valid email address, and the phone control is required and must be at least 10 digits long.

Now that we have our form set up, we can use it in our template:
<div class="register-form">
<form  (ngSubmit)="onSubmit()" [formGroup]="userform">
    <div class="form-group">
      <label>Name:</label>
      <input type="text" formControlName="name"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['name'].errors }"
      >
      <div *ngIf="submitted && f['name'].errors" class="invalid-feedback">
        <div *ngIf="f['name'].errors['required']">
          Name is required
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Email:</label>
      <input type="email" formControlName="email"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['email'].errors }"
      >
      <div *ngIf="submitted && f['email'].errors" class="invalid-feedback">
        <div *ngIf="f['email'].errors['required']">
          Email is required
        </div>
        <div *ngIf="f['email'].errors['email']">
          Email is not valid
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Phone:</label>
      <input type="tel" formControlName="phone"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['phone'].errors }"
      minlength="10" maxlength="11">
      <div *ngIf="submitted && f['phone'].errors" class="invalid-feedback">
        <div *ngIf="f['phone'].errors['required']">
              Phone is required
        </div>
            <div *ngIf="f['phone'].errors['minlength']">
              Phone must be at least 10 digits
            </div>
        </div>
    </div>
    <div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
  </div>
  </form>
</div>

In our template, we bind our formGroup to the userForm property in our component. We're also using the formControlName directive to bind each input field to its respective control.

We display validation messages for each control using Angular's *ngIf directive. We're checking if the control is invalid and either dirty or touched. If it is, we're displaying the relevant error message. For example, if the name control is required and the user has not entered anything, we'll display the "Name is required" error message.

We're also disabling the submit button if the form is invalid, which means validation errors are present.

Now that we have our form set up and displaying validation messages, we must handle form submission in our component. We'll create an onSubmit() method that will log the form data to the console:
onSubmit(): void {
    this.submitted = true;
    if (this.userform.invalid) {
        return;
    }
    console.log(JSON.stringify(this.userform.value, null, 2));
}

The sample screenshot is given below.


And that's it! We've created an Angular Reactive form with display validation with just a few lines of code. This form is highly customizable and can be expanded to collect more complex data easily.

With the assistance of ChatGPT, I am thrilled to have completed my third blog post.



AngularJS Hosting Europe - HostForLIFE :: TypeScript Versions In Angular

clock March 14, 2023 07:24 by author Peter

TypeScript is a superset of JavaScript and is widely used for developing large-scale applications. Angular, one of the most popular front-end frameworks is built using TypeScript. When working with Angular, knowing which version of TypeScript is being used in your project is important. In this blog post, we'll discuss identifying the TypeScript version in an Angular project.


Angular uses TypeScript as its primary language, meaning you will need to have TypeScript installed on your machine to develop Angular applications. Once you have TypeScript installed, you can check the version of TypeScript in your Angular project in the following ways:

Package.json file
The TypeScript version can be found in the package.json file of your Angular project. Open the package.json file and look for the "typescript" section. You will see the version of TypeScript that your Angular project is using. For example:
"devDependencies": {
   "typescript": "^4.3.5"
}

Angular CLI
You can also check the TypeScript version using the Angular CLI. Open your terminal and run the following command in the root directory of your Angular project:
ng version

This command will display the version of Angular, TypeScript, and other packages used in your project.

TypeScript Compiler
Another way to check the TypeScript version is to use the TypeScript compiler. Open your terminal and run the following command in the root directory of your Angular project:
tsc --version

This command will display the version of TypeScript installed on your machine. If the version displayed matches the version specified in the package.json file, that is the version used in your Angular project.

The following table summarizes version compatibility between Angular, TypeScript, and Node.

In conclusion, identifying the TypeScript version in an Angular project is important when developing large-scale applications. You can check the version of TypeScript using the package.json file, Angular CLI, or TypeScript compiler. Once you have identified the TypeScript version, you can use it to ensure that your code is compatible with the specific version of TypeScript being used in your Angular project.



AngularJS Hosting Europe - HostForLIFE :: How To Prevent XSS(Cross Site Scripting) Attacks In Angular?

clock March 9, 2023 08:08 by author Peter

Hello, here we are going to discuss how to prevent XSS attacks or Cross-Site Scripting in angular applications.

When we make any web application, then security is an important part of an application where we need to secure our web application from various attacks, one of which is an XSS attack or cross-site scripting attack.

What is XSS(Cross-Site Scripting)
XSS is a kind of injection attack. Let’s consider you have an application, and that application contains the contact form or registration form, where the user enters either their queries or their information in the input field or text Area field.

For example, what happens if a hacker gives a malicious script injected in the contact form text are Like the below script and clicks on submit
<script>alert(“XSS Attack");"</script>

Now, in this case, it will open a popup, and behind the screen, the website will send the request to the hacker’s computer with the current system cookies information or your crucial information will be in the attacker's system, even if you will not even realize it that XSS attack is happening.

Generally, an XSS attack happens on DOM elements (Object data model), like input, and text area Fields, so to prevent our website from an XSS attack we need to check whether the request contains the script or not, and if it contains then we need to handle such kind of condition.

How to prevent XSS attacks in Angular?

When we create an angular application then there is also a chance to happen an XSS attack, so let’s understand it with an example.

XSS Escaping/bypass security in Angular
To prevent cross-site scripting (XSS) attacks in the angular application, we can use the built-in angular cross-site scripting (XSS) protection.

This is enabled automatically by the angular CLI.

Now let’s create an angular application and write the below code in app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Angular15Service } from './angular15.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular 15 App';
    username = '';
    constructor() {}
    ngOnInit() {}
}


And write the below code in app.component.html
<p >{{title}}</p>
<label for="username">Name: </label>
<textarea id="username" [(ngModel)]="username" placeholder="Name"> </textarea>
<p>{{ username }}</p>

Here we can see, we are using Two-way data binding.

So when we give any value to the text area field, the same value we are printing in the paragraph using “interpolation”

When we are running the above code and give any value in TextArea then interpolation will not able to take input as HTML and display the full input as the plain text on your web application page, this mechanism is generally called “contextual escaping” like below
<script>alert(“XSS Attack");"</script>

Angular Input Sanitization
Now let’s take another example, not instead of taking username value instead of using interpolation, here we use innerHTML.

So now let’s change the HTML code like below
<p >{{title}}</p>
<label for="username">Name: </label>
<textarea id="username" [(ngModel)]="username" placeholder="Name"> </textarea>
<p [innerHTML]="username"></p>

Now let’s run your application and see the output, unlike the interpolation, [innerHTML] also shows the text Area input value.

If you give input values as <script> format in the text area like below
<script>alert(“XSS Attack");"</script>

You will see [InnerHTML] automatically understand the <script> tag as the unsafe tag and remove it and don’t print it like below, this is called “sanitization” in Angular.

After entering the above script, you see the inspect element, which shows

So in angular unlike [innerHTML], angular has another tag like [style], [href] as well which recognizes the <script> tag.

Sanitization function in Angular

Another way to prevent the XSS attack, we can use an angular build-in function called sanitization function like the bypassSecurityTrustHtml() function.

So to sanitize the <script> tag to the page, below is the example

Below is the app.component.html
<p >{{title}}</p>
<p [innerHTML]="username"></p>

Below is the app.component.ts code
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Angular15Service } from './angular15.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular 15 App';
    username = '';
    constructor() {}
    ngOnInit() {}
}


Here we have a taken username object type of SafeHtml, it is a marker interface that gives security to the web applications from untrusted script execution on the browser.

DomSanitizer is used to sanitize the DOM element.

When you run the above code, it contains <script> tag hence we can see on the browser it doesn’t print it on the browser.

So if you are working with the angular application, it automatically secures the angular application from an XSS attack.



AngularJS Hosting Europe - HostForLIFE :: Create Registration Form In Angular 14

clock March 3, 2023 09:52 by author Peter

This blog teaches how to create a registration form in Angular 14. Here's a basic example,


1. Create a new Angular component for your registration form. In the command line, run ng generate component registration-form.

2. Open the registration-form.component.html file and add the following code,
<form (ngSubmit)="onSubmit()">
  <label> Name: <input type="text" [(ngModel)]="name" name="name" required>
  </label>
  <br>
  <label> Email: <input type="email" [(ngModel)]="email" name="email" required>
  </label>
  <br>
  <label> Password: <input type="password" [(ngModel)]="password" name="password" required>
  </label>
  <br>
  <button type="submit">Submit</button>
</form>


3. Open the registration-form.component.ts file and add the following code:
import { Component } from '@angular/core';

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent {
  name: string;
  email: string;
  password: string;

  onSubmit() {
    console.log('Registration form submitted!');
    console.log(`Name: ${this.name}`);
    console.log(`Email: ${this.email}`);
    console.log(`Password: ${this.password}`);
  }
}


4. Save your changes and run ng serve to start the development server.
5. Open your browser and navigate to http://localhost:4200/registration-form. You should see the registration form displayed on the page.
6. Enter your name, email, and password into the form fields and click the Submit button. You should see the form data logged to the console.

Note that this is just a basic example, and you'll want to add more validation and error handling to your form in a real-world application. You may also want to store the user's registration data in a database or send it to a server via an HTTP request.



AngularJS Hosting Europe - HostForLIFE :: Angular Reactive Forms With Validation Example

clock March 1, 2023 07:08 by author Peter

First, you need to import the required modules in your component:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';


Then, you can create the form using the FormBuilder service:
@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      message: ['', Validators.required]
    });
  }
}


In this example, the myForm property holds the reactive form instance. The createForm method uses the FormBuilder service to create the form and define its fields with initial values and validators. The name field is required, the email field is required and must be a valid email address, and the message field is required.

Now, you can use this form in your template:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <label for="name">Name:</label>
  <input type="text" id="name" formControlName="name">
  <div *ngIf="myForm.get('name').invalid && (myForm.get('name').dirty || myForm.get('name').touched)">
    <div *ngIf="myForm.get('name').errors.required">Name is required.</div>
  </div>

  <label for="email">Email:</label>
  <input type="email" id="email" formControlName="email">
  <div *ngIf="myForm.get('email').invalid && (myForm.get('email').dirty || myForm.get('email').touched)">
    <div *ngIf="myForm.get('email').errors.required">Email is required.</div>
    <div *ngIf="myForm.get('email').errors.email">Invalid email format.</div>
  </div>

  <label for="message">Message:</label>
  <textarea id="message" formControlName="message"></textarea>
  <div *ngIf="myForm.get('message').invalid && (myForm.get('message').dirty || myForm.get('message').touched)">
    <div *ngIf="myForm.get('message').errors.required">Message is required.</div>
  </div>

  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>


In this example, the formGroup directive binds the myForm instance to the form element. The formControlName directive binds each form control to the corresponding field in the myForm instance. The *ngIf directives display error messages for each field if it's invalid and has been touched or is dirty.

Finally, you can handle the form submission in your component:
onSubmit() {
  // Do something with the form data
}


This is a basic example, but you can add more validation rules and custom validators as needed.



AngularJS Hosting Europe - HostForLIFE :: Two Factor Google Authenticator Using ASP.NET Core And Angular

clock February 28, 2023 08:07 by author Peter

Google Authenticator is a free security application that generates unique codes for two-factor authentication (2FA) purposes. 2FA is an added layer of security used to verify a user's identity by requiring them to provide two pieces of evidence: something they know (such as a password) and something they have (such as a smartphone).


The Google Authenticator app generates a time-based one-time password (TOTP) valid for a short period, typically 30 seconds. This code can be used as the second factor in a 2FA setup, along with a password or other first factor.

To use Google Authenticator, you must first enable 2FA on your account or app. Then, download and install the Google Authenticator app on your smartphone or tablet. When you log in to your account or app, you will be prompted to enter the unique code generated by the app along with your password. This ensures that even if someone knows your password, they cannot log in without access to the second factor code generated by the Google Authenticator app.

Overall, 2FA adds an extra layer of security to your online accounts and helps protect you against various online attacks, such as phishing and password theft.

To implement 2-Factor Google Authenticator using Asp Net Core and Angular, you can follow the below steps,

1. Install the Google Authenticator NuGet package,
Install-Package GoogleAuthenticator

2. In the Asp Net Core application, create a class named "TwoFactorAuthenticatorService" and add the following code,
using Google.Authenticator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public class TwoFactorAuthenticatorService
{
    public string GenerateQrCodeUri(string email, string secretKey)
    {
        var tfa = new TwoFactorAuthenticator();
        return tfa.GenerateQrCodeUri(email, secretKey);
    }

    public bool ValidateTwoFactorPin(string secretKey, string twoFactorCode)
    {
        var tfa = new TwoFactorAuthenticator();
        return tfa.ValidateTwoFactorPIN(secretKey, twoFactorCode);
    }

    public string GenerateNewSecretKey()
    {
        var tfa = new TwoFactorAuthenticator();
        var setupCode = tfa.GenerateSetupCode("My App", "My User", "mysecretkey", 300, 300);
        return setupCode.Secret;
    }
}


3. In the Angular application, create a component named "TwoFactorAuthenticatorComponent" and add the following code,
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-two-factor-authenticator',
  templateUrl: './two-factor-authenticator.component.html',
  styleUrls: ['./two-factor-authenticator.component.css']
})
export class TwoFactorAuthenticatorComponent {
  email: string;
  secretKey: string;
  qrCode: string;
  twoFactorCode: string;

  constructor(private http: HttpClient) { }

  generateSecretKey() {
    this.http.get('/api/twofactorauthenticator/generatesecretkey').subscribe((result: any) => {
      this.secretKey = result;
      this.qrCode = 'https://chart.googleapis.com/chart?chs=300x300&chld=M|0&cht=qr&chl=' + encodeURIComponent(result);
    });
  }

  validateTwoFactorCode() {
    this.http.post('/api/twofactorauthenticator/validatetwofactorcode', { secretKey: this.secretKey, twoFactorCode: this.twoFactorCode }).subscribe((result: any) => {
      if (result) {
        alert('Valid code!');
      } else {
        alert('Invalid code!');
      }
    });
  }
}


4. In the Angular application, create a template for the "TwoFactorAuthenticatorComponent" component and add the following code,
<div>
  <label>Email:</label>
  <input type="text" [(ngModel)]="email">
</div>
<div>
  <button (click)="generateSecretKey()">Generate Secret Key</button>
</div>
<div *ngIf="secretKey">
  <img [src]="qrCode">
  <p>Secret Key: {{ secretKey }}</p>
</div>
<div>
  <label>Two Factor Code:</label>
  <input type="text" [(ngModel)]="twoFactorCode">
  <button (click)="validateTwoFactorCode()">Validate Two Factor Code</button>
</div>


5. In the Asp Net Core application, create a controller named "TwoFactorAuthenticatorController" and add the following code:
using Microsoft.AspNetCore.Mvc;
using QRCoder;
using System;
using System.Drawing;
using TwoFactorAuthenticator;

namespace YourNamespace.Controllers
{
    public class TwoFactorAuthenticatorController : Controller
    {
        // Action method to generate the QR code for the user to scan and set up their Two-Factor Authentication
        public IActionResult GenerateQRCode()
        {
            // Generate the Two-Factor Authentication secret key
            var secretKey = new Base32Encoder().Encode(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10)));

            // Generate the QR code for the user to scan
            var qrCodeGenerator = new QRCodeGenerator();
            var qrCodeData = qrCodeGenerator.CreateQrCode($"otpauth://totp/YourAppName:YourUserName?secret={secretKey}&issuer=YourAppName", QRCodeGenerator.ECCLevel.Q);
            var qrCode = new QRCode(qrCodeData);
            var qrCodeImage = qrCode.GetGraphic(20);

            // Return the QR code image to the user
            return File(qrCodeImage, "image/png");
        }

        // Action method to verify the user's Two-Factor Authentication code
        [HttpPost]
        public IActionResult VerifyCode(string code)
        {
            // Get the user's Two-Factor Authentication secret key from the database or other storage location
            var secretKey = "yourSecretKey";

            // Verify the One-Time Password (OTP) entered by the user
            var tfa = new TwoFactorAuthenticator();
            var result = tfa.ValidateTwoFactorPIN(secretKey, code);

            // If the OTP is valid, redirect the user to their account or other authorized page
            if (result)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                // If the OTP is invalid, return an error message to the user
                ModelState.AddModelError("code", "The code entered is invalid.");
                return View();
            }
        }
    }
}


This article discusses the implemention 2-Factor Google Authenticator using Asp Net Core and Angular in detail.



European Visual Studio 2022 Hosting - HostForLIFE :: Sharing Web Apps Using Dev Tunnels In Visual Studio 2022

clock February 22, 2023 07:00 by author Peter

Sometimes we want to share what we are doing, the changes that we are performing, or a proof of concept with others. To do this, we need to publish our app or share the screen with others and show step-by-step what we are doing and how it works. Ngrok is an application for this scenario; it's petty simple to use and free with some limitations.

In Visual Studio 2022, we have now the possibility to share quickly our web application with a https public URL.

Since this is a preview feature in Visual Studio we need to navigate to Tools -> Manage preview features

And check the option "Enable dev tunnels for web applications"

After that in our ASP.NET core web application, we need to open launchsettings.json and add 2 properties to the general profile to include now the functionality to open the application using dev tunnels, or you can also create a new profile.

Example
"profiles": {
    "WebApplication1": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": true,
        "applicationUrl": "https://localhost:7211;http://localhost:5258",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "devTunnelEnabled": true,
        "devTunnelAccess": true
    },
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }
}

Finally, you can now run the profile changed or the new profile that includes the 2 dev tunnel properties and run the application in a public URL that other people can see.

We need to confirm that we want to use the dev tunnel in the browser

This is the website running using dev tunnels:

You can now share this site with others, every time that you can execute your project Visual Studio will generate a new URL.



AngularJS Hosting Europe - HostForLIFE :: How To Use APP_INITIALIZER In Angular?

clock February 21, 2023 07:21 by author Peter

Angular comes bundled with an app_initializer token, allowing developers to execute some code before the application starts running. It provides a way to load data, perform authentication, or configure the application environment before the application is rendered in the browser.


The app_initializer token is defined as a provider in the @angular/core module. It takes a function as an argument and returns a Promise or an Observable. When the application starts, Angular invokes the app_initializer provider and waits for the Promise or Observable to resolve before rendering the application.

To use app_initializer in your application, you must define a function that performs the initialization tasks and returns a Promise or Observable. For example, you want to load some configuration data before the application starts. You can define an app_initializer provider in your app.module.ts file as follows:
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './app-config.service';

export function initialize(appConfig: AppConfigService) {
  return () => appConfig.load();
}

@NgModule({
  providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: initialize,
      deps: [AppConfigService],
      multi: true
    }
  ],
  ...
})
export class AppModule { }


In the above example, we define an AppConfigService that loads configuration data from a remote server. The load method returns a Promise that resolves when the data is loaded. We are also defining an initialize function that takes the AppConfigService as a dependency and returns a function that calls the load method.

The APP_INITIALIZER provider is then defined in the providers array of the AppModule. We pass the initialize function as the useFactory parameter and specify the AppConfigService as a dependency in the deps array. We also set the multi parameter to true to allow multiple initialization functions.

With the above setup, when the application starts, Angular will invoke the initialize function and call the load method of the AppConfigService. Angular will wait for the Promise returned by the load method to resolve before rendering the application.

In conclusion, the app_initializer feature in Angular is a powerful tool that allows developers to perform initialization tasks before the application starts running. It provides a clean and efficient way to initialize your Angular application. By defining an app_initializer provider, you can execute code to load data, perform authentication, or configure the application environment.



AngularJS Hosting Europe - HostForLIFE :: How To Create Password And Confirm Password Matching Validation In Angular?

clock February 17, 2023 08:34 by author Peter

In this article, we will learn how to create a password and confirm password matching validation in an Angular application. Password and confirm password matching validation is generally required in the registration form and password reset or create form.

Prerequisites
    Basic knowledge of Angular
    Visual Studio Code
    Node and NPM installed
    Bootstrap

For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:

Create an Angular Project
Let's create a new angular project by using the following command.
ng new PassValidationExample

Open a project in Visual Studio Code using the following commands.
cd PassValidationExample
Code .


Now in Visual Studio, your project looks as below.

 

 

 

For validation, we need to import Validators from  '@angular/forms'
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

App.component.html
<div class="container">

    <div style="margin: 30px">
        <h1 class="ion-text-center">Register</h1>

        <form [formGroup]="loginForm">
            <div class="form-group">
                <label>First Name*</label>
                <input class="form-control" formControlName="fname" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.fname">
                    <div class="error-message" *ngIf="loginForm.get('fname').hasError(error.type) && (loginForm.get('fname').dirty || loginForm.get('fname').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Last Name*</label>
                <input class="form-control" formControlName="lname" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.lname">
                    <div class="error-message" *ngIf="loginForm.get('lname').hasError(error.type) && (loginForm.get('lname').dirty || loginForm.get('lname').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Email Id*</label>
                <input class="form-control" formControlName="email" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.email">
                    <div class="error-message" *ngIf="loginForm.get('email').hasError(error.type) &&
    (loginForm.get('email').dirty || loginForm.get('email').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Password*</label>
                <input class="form-control" formControlName="password" type="password" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.password">
                    <div class="error-message" *ngIf="loginForm.get('password').hasError(error.type) && (loginForm.get('password').dirty || loginForm.get('password').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Confirm Password*</label>
                <input class="form-control" formControlName="confirmpassword" type="password" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.confirmpassword">
                    <div class="error-message" *ngIf="loginForm.get('confirmpassword').hasError(error.type) && (loginForm.get('confirmpassword').dirty || loginForm.get('confirmpassword').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>
      <pre>
        Form Error - {{ loginForm.errors | json }}
      </pre>
            <button class="form-control btn btn-primary" [disabled]="!loginForm.valid">Signup</button>
        </form>
    </div>
</div>


App.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  loginForm: FormGroup;

  error_messages = {
    'fname': [
      { type: 'required', message: 'First Name is required.' },
    ],

    'lname': [
      { type: 'required', message: 'Last Name is required.' }
    ],

    'email': [
      { type: 'required', message: 'Email is required.' },
      { type: 'minlength', message: 'Email length.' },
      { type: 'maxlength', message: 'Email length.' },
      { type: 'required', message: 'please enter a valid email address.' }
    ],

    'password': [
      { type: 'required', message: 'password is required.' },
      { type: 'minlength', message: 'password length.' },
      { type: 'maxlength', message: 'password length.' }
    ],
    'confirmpassword': [
      { type: 'required', message: 'password is required.' },
      { type: 'minlength', message: 'password length.' },
      { type: 'maxlength', message: 'password length.' }
    ],
  }

  constructor(
    public formBuilder: FormBuilder
  ) {
    this.loginForm = this.formBuilder.group({
      fname: new FormControl('', Validators.compose([
        Validators.required
      ])),
      lname: new FormControl('', Validators.compose([
        Validators.required
      ])),
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
      password: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
      confirmpassword: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
    }, {
      validators: this.password.bind(this)
    });
  }

  ngOnInit() {
  }

  password(formGroup: FormGroup) {
    const { value: password } = formGroup.get('password');
    const { value: confirmPassword } = formGroup.get('confirmpassword');
    return password === confirmPassword ? null : { passwordNotMatch: true };
  }

}


App.component.css
p {
  font-family: Lato;
}
.error-message {
  color: red;
}
input.ng-touched.ng-invalid {
  border: 1px solid red;
}

Now run the project using the following command
npm start

In this article, I have discussed the implementation of password and confirm password matching validation in Angular application.



Node.js Hosting - HostForLIFE :: .Net Core Vs Node

clock February 15, 2023 09:18 by author Peter

.NET Core and Node.js are two popular technologies for building APIs (Application Programming Interfaces). Both have their strengths and weaknesses, and the choice between them depends on the specific requirements of a project.

.NET Core is a cross-platform, open-source framework for building modern applications. It is developed by Microsoft and is part of the .NET ecosystem. .NET Core is based on C#, a statically-typed language. It supports LINQ (Language Integrated Query) and Entity Framework, making it easier to query data. .NET Core also provides a strong security model, built-in support for WebSockets, and the ability to run on Windows, Linux, and macOS.

Node.js, on the other hand, is an open-source, cross-platform JavaScript runtime environment. It is event-driven and non-blocking, making it highly efficient for real-time applications. Node.js has a vast and growing ecosystem, with numerous packages and tools available for a variety of purposes, including building APIs.

When it comes to building APIs, .NET Core is a good choice if you're looking for a framework with a strong security model, good performance, and the ability to handle large amounts of data. .NET Core is also a good choice if you're already familiar with C# and the .NET ecosystem, as this will reduce the learning curve.

Node.js, on the other hand, is a good choice if you're looking for a fast and efficient API that can handle real-time data and can be scaled horizontally. Node.js is also a good choice if you're already familiar with JavaScript and the Node.js ecosystem, as this will reduce the learning curve.

Similarities between .Net Core and Node

Despite their differences, .NET Core and Node.js have some similarities as well. Here are some of the most notable similarities between the two technologies:

Cross-platform compatibility
Both .NET Core and Node.js are cross-platform technologies, which means that they can run on multiple operating systems, including Windows, Linux, and macOS.

Open-source

Both .NET Core and Node.js are open-source technologies, which means that their source code is available for anyone to use, modify, or contribute to.

Large and active communities
Both .NET Core and Node.js have large and active communities of developers, which means that there is a wealth of knowledge, tools, and resources available for these technologies.

Fast and efficient

Both .NET Core and Node.js are designed to be fast and efficient, making them well-suited for building high-performance applications, including APIs.

Support for modern web technologies
Both .NET Core and Node.js support modern web technologies, such as REST and WebSockets, making it easy to build modern, scalable APIs.

Difference between .Net Core and Node

While .NET Core and Node.js have some similarities, they also have some notable differences that make them well-suited for different types of projects. Here are some of the most important differences between the two technologies,

Language
.NET Core is based on C#, a statically-typed language, while Node.js is based on JavaScript, a dynamically-typed language. This can impact the development experience and the performance of the resulting application.

Performance

.NET Core is generally considered to be a more performant framework, especially for applications that require handling large amounts of data. Node.js, on the other hand, is designed for real-time, event-driven applications and is highly efficient for these types of applications.

Ecosystem
.NET Core is part of the .NET ecosystem, which includes a large number of libraries, tools, and frameworks for building applications. Node.js has a growing and vibrant ecosystem of its own, with a large number of packages and tools available for a wide range of purposes.

Security
.NET Core provides a strong security model, with built-in support for authentication, authorization, and encryption. Node.js, while secure, does not provide the same level of security features out-of-the-box as .NET Core.

Scalability
Node.js is designed to be highly scalable, with the ability to run multiple instances of the application on multiple machines to handle increased traffic. .NET Core also supports scalability, but it may require additional work to achieve the same level of scalability as Node.js.

.NET Core and Node.js are both powerful technologies for building APIs, but they have some important differences that make them well-suited for different types of projects. The choice between the two will depend on the specific requirements of a project, including the desired performance, security, scalability, and skills of the development team.

In conclusion, despite the differences between .NET Core and Node.js, the two technologies have some similarities, including cross-platform compatibility, open-source nature, large and active communities, fast and efficient performance, and support for modern web technologies.

Conclusion

In conclusion, the choice between .NET Core and Node.js depends on the specific requirements of a project. .NET Core is a good choice for projects that require a strong security model and good performance, while Node.js is a good choice for projects that require real-time data and scalability. Before making a choice, it is important to consider the specific requirements of a project and the skills of the development team.

Thanks for reading my article.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in