What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include:

  • All inputs are required
  • Email address should be valid
  • Name should only contain letters
  • Password must have a minimum of 8 characters, at least 1 uppercase letter, 1 lowercase letter, and 1 number

Additionally, I would like to display a message under every invalid input using

<div id="na"></div>
. How can I achieve this?

Below is my HTML file:

<h2 class="text-center">Inscription</h2>
<div class="row">
... // (HTML code here)
</div>

Here is my TypeScript file:

import { Component, OnInit } from '@angular/core';
... // (TypeScript code here)

Thank you in advance.

Answer №1

this is the code snippet for setting up form validation in Angular:</p>

this.angForm = this.fb.group({
email: ['', Validators.required, Validators.email],
password: ['', Validators.required, Validators.minLength(8), Validators.pattern("(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}")],
name: ['', Validators.required, Validators.pattern('^[a-zA-Z ]*$')],
mobile: [null, Validators.required, Validators.minLength(10), Validators.maxLength(10)]
});

In your HTML file, make sure to include appropriate error messages next to each form field:</p>

<span class="text-danger"
       *ngIf="(angForm.name.touched || submitted) && 
                angForm.name.errors?.required">
            Name is required
</span>
        
<span class="text-danger"
       *ngIf="((angForm.password.touched || submitted) && 
                angForm.password.errors?.required )|| (angForm.invalid && submitted)">
            Password must contain at least one number and one uppercase and lowercase letter, and be at least 8 characters long.
</span>

Ensure that similar error messages are set up for email and mobile fields as well.</p>

For a more detailed guide on how to validate Angular reactive forms, check out this resource:
<a href="https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/" rel="nofollow noreferrer">https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/</a></p>

Answer №2

reply to Rothitha If you prefer not to utilize the "auxiliary variable" submitted, you can incorporate it in the submit function.

submit(form:FormGroup)
{
   if (form.invalid)
      form.markallAsTouched()
   else
   {
      ..doSomething..
   }
}

To improve error management and get rid of the cumbersome

*ngIf="angForm.get('password').touched && angForm.get('password').touched"
, we can implement a similar technique as Bootstrap for handling errors.

We employ a .css like

.invalid-feedback
{
   display:none
}
.ng-invalid.ng-touched ~ .invalid-feedback
{
  display: block;
}

Along with an HTML structure like

<!--enclose everything within a div-->
<div>

    <!--a label-->
    <label for="email">Email</label>

    <!--an input field-->
    <input id="email" formControlName="email">

    <!--a div with class="invalid-feedback-->
    <div class="invalid-feedback">

        <!--use *ngIf for multiple validators-->
        <div *ngIf="angForm.controls.email.errors?.required">Email is required</div>
        <div *ngIf="angForm.controls.email.errors?.email">Invalid email format</div>
    </div>

</div>

For reference, check out this stackblitz link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The website is failing to extend and reveal content that is being concealed by jQuery

I'm currently diving into the world of Javascript and jQuery, attempting to create a functionality where upon clicking the submit button, the website dynamically expands to display search information. Although the feature is still in progress, I am ut ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Dealing with issues of toggling visibility with jQuery when using a dropdown menu

Inside a hidden drop down div, the focus is on "DC" right now. In the image below, we are looking at sales: HTML: <td class="edit"> <select class="touch" style="display: none;"> <option value="11">Rebuying</option><option value ...

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

Jasmine - What is the best way to simulate a finally block?

After creating a controller in my test, I encountered an issue with the updateActionList function... this.createScope = function(scope) { if (scope) { this.scope = scope; } else { this.scope = $rootScope.$new(); } this.contro ...

Storing basic input values for a function

I am currently working on developing a versatile method that is capable of accepting any number of parameters, while storing the input type for future use. Let's take a look at an example: const customizedFunction = <A extends any[]>(innerFunct ...

Duplicate Key Error in MongoDB

I am currently developing a service that enables multiple events to store data on MongoDB. Each event creates new collections on MongoDB when it occurs, and if the same event needs to store different data, a new document in MongoDB is created. Below is th ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

Angular Select Component with Input Value

In a small part of my code, I have a select tag with multiple option elements. This allows me to loop through the elements and select the one that I require. The tricky part is that I need to implement a search functionality within this select. Essential ...

Angular template error: Potential is present but not defined

Encountering an issue with my Angular application's template file (dashboard.component.html). The error message reads "Object is possibly 'undefined'." Here's the portion of the template that seems to be causing the problem: <div> ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

When attempting to create a fresh NestJS module, a message pops up stating: "An error occurred while

Currently running MacOS Monterey with the M1 chip as my OS. I installed NestJS CLI using the command: sudo npm install -g @nestjs/cli When creating a new Nest project with nest new message, everything goes smoothly. However, when attempting to generate a ...

Retrieve the identification number for each item within my array

I am working with an array of objects, each having a unique ID. My goal is to find the index of each object in the array. I am currently using Angular, however, I am restricted from using $index for this particular task. $scope.getObjectIndex = fun ...

Example of Signature in TypeScript Function Declaration

While going through this documentation, I found myself puzzled by the concept of having a parameter that can be both an object and a function in JavaScript. type DescribableFunction = { description: string; (a: any): boolean; }; function doSomething( ...