Preventing form submission in Angular 7 until all validations have been successfully completed

Exploring Angular for the first time has been quite a journey. I've delved into this, this, and this question in depth, but none of them quite fit my needs as they rely heavily on jquery. My form is a straightforward registration form comprising only four basic fields: Username, password, confirm password, zipcode, and a submit button. To maintain clarity, I have uploaded the necessary files to GitHub.

  1. app.component.html
  2. app.component.ts
  3. app.module.ts

I've implemented validators for password and zipcode separately in

  1. validator.ts

The validations are indeed functioning correctly. However, the issue lies in the fact that the form is still submitting even when there are validation errors on the frontend. Attached is a screenshot highlighting this concern. Any recommendations or hints would be greatly appreciated.

PS: I'm currently following along with this YouTube tutorial.

https://i.sstatic.net/CAthq.png

Answer №1

To start, you will want to deactivate the button.

<button type="submit" class="btn btn-primary" (click)="onSubmit()" [disabled]="!form.valid">Submit</button>

Then, make sure to include a condition prior to submitting the form.

  onSubmit(){
    if (!this.form.valid) return;

    // console.log(this.form.controls.zip);
    this.form.markAsTouched();
    console.log(this.form.value);

  }

Lastly, ensure that you add the specified attribute to your form:

<form [formGroup]="form" novalidate>

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

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

Tips for providing a Story with a TemplateRef as an input parameter?

Currently, I am attempting to create a narrative that involves utilizing a component that accepts a TemplateRef as an @Input. However, I am encountering difficulties in understanding how to achieve this. TestComponent @Component({ selector: 'test&a ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...

Exporting multiple sheets using Angular's ngx-export-as functionality

Currently utilizing ngx-export-as in my Angular project and I am looking to export an Excel file with multiple sheets. How can I achieve this export functionality? I have raised a concern regarding this on GitHub. ...

What is the best way to implement strong typing for a socketIO server in TypeScript?

Is there a way to properly type the private property private io in Typescript to prevent the error message Property 'io' has no initializer and is not definitely assigned in the constructor import fastify, { FastifyReply, FastifyRequest } from &q ...

Dropdown within Datatable does not automatically select the bound option [PrimeNG]

Hey there! I'm a trainee just entering the world of frontend development, so apologies in advance if my question seems silly or if my code looks messy (any corrections are greatly appreciated). In my project, I have a Dropdown element inside a Datata ...

Using Angular to incorporate HighCharts for a gauge chart

I'm currently working on an Angular project where I need to display a statistic using a gauge chart. The thing is, I'm utilizing the HighCharts library and it's worth mentioning that I've successfully used other types of charts from Hig ...

An issue occurred while attempting to retrieve Firebase data using an HTTP GET request

When trying to retrieve my data from firestore using an HTTP get request, I encountered an error. It might be helpful if my data in firestore was stored in JSON format. I'm not sure if this is feasible. <!DOCTYPE html> <html lang="en"> ...

Experience the convenience of selecting multiple rows with checkboxes, while enjoying the simplicity of selecting a single row by clicking

Hey there! I'm looking to enable multiple selection using checkboxes and single selection by clicking on a row. Does anyone know how I can achieve this within the same table? Check out this link for some ideas ...

The Vue3 module does not have any exported members available

I am seeking assistance with a Vue component. I have encountered an error message that states: Failed to compile. src/components/Btn/Btn.vue:11:14 TS2305: Module '"../../typings/button-type"' has no exported member 'ButtonType&apo ...

The mysterious case of Angular Material 15 MatSort being constantly elusive

Having used MatSort in my application's table for the past 2 years, I recently updated to version 15 and encountered a problem. In the AfterViewInit event, I discovered that MatSort is always undefined now. Despite importing the MatSortModule, the iss ...

The symbol 'submitted' has not been declared

I have been working on implementing client-side validation in Angular using ReactiveForms. I encountered an error stating "Identifier 'submitted' is not defined. 'FormGroup' does not contain such a member" on this line: <div *ngIf=&q ...

A guide on implementing code sharing in NestJS using Yarn Workspaces

I'm currently working on a proof of concept for a basic monorepo application. To structure my packages, I've decided to use Yarn Workspaces instead of Lerna as it seems more suitable for my needs. One of the packages in my setup is shared, which ...

What is the best way to create a T-shaped hitbox for an umbrella?

I've recently dived into learning Phaser 3.60, but I've hit a roadblock. I'm struggling to set up the hitbox for my raindrop and umbrella interaction. What I'd love to achieve is having raindrops fall from the top down and when they tou ...

What steps can be taken to troubleshoot the error message "InjectionToken angularfire2.app.options! not found" during testing of Firestore in Angular?

During my Angular test, I encountered an issue with a component and a service that utilizes Firestore. Here is the error message from my ItemService: NullInjectorError: R3InjectorError(DynamicTestModule)[ItemService -> AngularFirestore -> InjectionTo ...

Using Angular 2 alongside Twitter Bootstrap

What is the recommended approach for integrating the Twitter Bootstrap library with Angular 2 framework? There are typically two main methods: Begin by structuring the HTML using Bootstrap containers and then embed Angular components within these contain ...

Include type annotations for prototyped methods

In my Node module, I have a JavaScript function that looks like this (simplified): index.js: var BadRequestError = require('./error') Guard.prototype = { /** * * @param {String} property * @return {_middleware} */ check: funct ...

Using Angular 2 to implement bi-directional binding for arrays of objects in ngFor with editable input fields

I'm just starting out with Angular 2 and I'm attempting to create a list of editable objects using ngFor, where users can add new objects and save the data. Here is the initial data: business: { email: "<a href="/cdn-cgi/l/email-protection" c ...

What is the process for specifying a dependency on an ng-metadata module?

I am currently working on a project that is utilizing ng-metadata for creating a few Angular 1.5 modules. One of the test modules/components in this project has the following structure: import { NgModule, Component, Inject, Input, Output, EventEmitter } f ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...