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

Safari's anchor links tend to leap higher than necessary

One of the anchor links on my website is behaving strangely in Safari, both on iPhone and MacOS. Instead of scrolling to the correct position of the anchored div, it scrolls to a random location around 400-500px higher than it should be. All other anchor l ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below: // tslint:disable-next-line:max-line-length constructor(public addCustomerDialog: MatDialog, private router: Router, private rout ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

Navigating through alterations in intricate data utilizing the BehaviorSubject concept

If I have a Service that offers a BehaviorSubject to any component needing the most up-to-date version of certain data, how can these components differentiate what changed in the data when they receive notifications? export class DataService { pri ...

Retrieve select options only upon clicking

Essentially, I have a default value that needs to be loaded into a select element and then make an API call to load the rest only when the select is clicked. <select (click)="getSubevents(market_uri)"> <option *ngFor="let subeven ...

Display the default text using ngx-translate if a key is not found or while the translation file is loading

Currently in the process of setting up a brand new Angular 7 application. I am interested in establishing a default text for translation purposes. Specifically, when utilizing the translation {{ 'wait' | translate }}, I would like to ensure that ...

Having trouble retrieving a path reference from Firebase Storage using getDownloadURL() in React Native?

I am having trouble uploading some images and retrieving them using the .getDownloadURL() method. Oddly enough, it works perfectly fine in another part of my application when I update the user's profile picture, but for some reason, it fails in the co ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Pausing a running function in React

Exploring Visual Sorting Algorithms In the process of creating a visual sorting algorithms tool for educational purposes, I have developed a function called sortArray() that handles the animation of the sorting process on arrays. The functionality is evid ...

"Change the value of a style setting in React to 'unset

One of the components has CSS properties such as `right` and `bottom` that are set with a classname. I tried to override these values using the `style` prop but have only been successful in setting numerical values like `10px` or `0px`, not `unset`. Wha ...

How should trpc query calls be implemented in a Next.js application for optimal performance?

Transitioning from pure frontend React to Next.js, I am currently working on implementing trpc calls to the backend. While this is a familiar process for me, it seems that the approach I've been using may not be appropriate in this case. const [weight ...

Is it possible to exchange code among several scripted Grafana dashboards?

I have developed a few customized dashboards for Grafana using scripts. Now, I am working on a new one and realizing that I have been duplicating utility functions across scripts. I believe it would be more efficient to follow proper programming practices ...

What is the most efficient way to switch between different views in AngularJS while preserving the data in the views'

Every time I navigate from page1.html to page2.html in AngularJS and then return back to page1.html, my page model data disappears. Can someone please help me figure out how to preserve this data? I've looked at other questions on this topic but coul ...

Changing the dimensions of a div according to the container's size

I'm currently working on a project that involves an HTML video player with custom Javascript controls, utilizing SVG graphics for the backgrounds. However, I've encountered an issue with using the css calc() function to resize the divs based on t ...

What is the best way to incorporate a variable in the find() method to search for similar matches?

I've been working on a dictionary web application and now I'm in the process of developing a search engine. My goal is to allow users to enter part of a word and receive all similar matches. For instance, if they type "ava", they should get back ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Three.js - Exploring the Significance of "THREE" within the THREE.scene Framework

Just starting out in JavaScript and experimenting with animations using three.js library. I'm trying to grasp the meaning behind: const scene = new THREE.Scene(); Why is the "THREE" necessary in THREE.Scene? Could we not simply write const scene = n ...

Can we display the chosen form values before submitting?

Want to implement a confirmation message for users before submitting their form using onClick="return confirm('are you sure ?')". The basic form structure is as follows: <form> <Select name='val[]' class='select'> ...