Does the submit button function even without filling in the required fields?

After creating a form with 20 fields, I encountered an issue. Out of those fields, there are 10 mandatory ones. When attempting to submit the form, only the mandatory input fields display a red border without showing an error message. Despite this, the submission still successfully sends data to the server.

input.submitted.ng-invalid
{
  border:1px solid #f00;
}
form.submitted .ng-invalid
{
border:1px solid #f00;
}
input.ng-touched.ng-invalid {
    border-color:red;
}
   input.ng-touched.ng-valid {
border-color:green;
  } 

this.form = this.formBuilder.group({
      Logo: [null, [Validators.required]], TournamentType: [null, Validators.required],
      TournamentName: [null, Validators.required], TournamentStartDate: [null, [Validators.required]],
      TournamentEndDate: [null, [Validators.required]], StarStatus: [null, [Validators.required]],
      EntryStartDate: [null, [Validators.required]], EntryEndDate: [null, [Validators.required]],
      Venue: [null, [Validators.required]], Address: [null, [Validators.required]],
      enfee: [null, [Validators.required]], PlayersCategory: [null, [Validators.required]],
      latitude: [null, [Validators.required]], longitude: [null, [Validators.required]]
    });

This is how it appears in my HTML:

                <div class="form-group" [formGroup]="form">
                        <label class="lable label-default">Logo<span style="color: red">*</span></label><br>
                        <img [src]='imageURl' style='width:160px;height:140px;'>
                        <input type="file" id='Logo' formControlName="Logo"  name="Logo"  style="margin-top:10px" accept="image/*"
                        (change)="handleFileInput($event)"
                        [ngClass]="{'form-submitted': formSubmitted}" [(ngModel)]='tourDetails.Logo' required />
                </div>
                <div class="form-group" [formGroup]="form">
                        <label class="label label-default" for="tour-type">Tournament Type<span style="color: red">*</span></label>
                        <select id="TournamentType" formControlName="TournamentType" class="form-control" [(ngModel)]="tourDetails.TournamentType"
                            name='TournamentType'  [ngClass]="{'form-submitted': formSubmitted}"
                             required>
                            <option value='' selected>Select</option>
                            <option *ngFor="let TT of tourType" value={{TT.value}}>{{TT.name}}</option>
                        </select>
                </div>  

                <div class="form-group" [formGroup]="form">
                    <label class="lable label-default">Tournament Name<span style="color: red">*</span></label>
                    <input id="TournamentName" class="form-control" name='TournamentName' formControlName="TournamentName"
                     [(ngModel)]='tourDetails.TournamentName'  [ngClass]="{'form-submitted': formSubmitted}"
                     required />
                </div>

                <div class="form-group inputWithIcon" [formGroup]="form">
                    <label class="lable label-default">Tournament Start Date<span style="color: red">*</span></label>
                    <input class="form-control input-wrapper " bsDatepicker type="text" name='TournamentStartDate'
                        [(ngModel)]="tourDetails.TournamentStartDate" autocomplete='off' [bsConfig]="{ dateInputFormat: 'DD-MM-YYYY' }"
                        [outsideClick]="true" [maxDate]='tourDetails.TournamentEndDate'
                          formControlName="TournamentStartDate" [ngClass]="{'form-submitted': formSubmitted}" required> 
                </div>

                <div class="form-group inputWithIcon" [formGroup]="form">
                    <label class="lable label-default">Tournament End Date<span style="color: red">*</span></label>
                    <input class="form-control input-wrapper" bsDatepicker type="text" name='TournamentEndDate'
                        [(ngModel)]="tourDetails.TournamentEndDate"  autocomplete='off' [bsConfig]="{ dateInputFormat: 'DD-MM-YYYY' }"
                        [outsideClick]="true" [minDate]='tourDetails.TournamentStartDate'
                         formControlName="TournamentEndDate" [ngClass]="{'form-submitted': formSubmitted}" required>
                </div>

The desired outcome: Upon clicking the submit button, the form should prevent submission if any mandatory fields are left empty. Additionally, the mandatory input fields ought to display an error message saying "Please fill this required field" along with a red border around them.

Answer №1

you should include a (*)

<div *ngIf="form.get('Logo').invalid && form.get('Logo').touched">Required</div>

Additionally, in the submit function

submit()
{
    if (this.form.invalid)
        this.form.markAsUntouched()
    else
    {
         ...the form is valid...
    }
}

(*) Another option is to create a component

@Component({
  selector: 'app-error',
  template: `
    <small class="form-text text-danger" *ngIf="isInvalid" >
       <ng-content></ng-content>
    </small>
`
})
export class ErrorComponent {

  @Input('controlName') controlName: string;
  @Input('error') error: string

  control: FormControl
  visible: boolean = false;

  get isInvalid() {
    const control = this.form.form.get(this.controlName);
    return control.touched && control.invalid && 
        (this.error ? control.errors[this.error] : true);
  }
  constructor(@Optional() @Host() private form: FormGroupDirective) { }

Usage example

<app-error controlName="Logo">Logo required.</app-error>

<!---or if you has severals errors-->
<!-- imagine a control email with [Validators.required,Validators.email] -->

<app-error controlName="email" error="required">Email required.</app-error>
<app-error controlName="email" error="email">Email invalid.</app-error>

Answer №2

<div class="inputWithIcon form-group" [formGroup]="form">
    <lable class="label label-default">Tournament End Date<span style="color: red">*</span></lable>
    <input class="input-wrapper form-control" bsDatepicker type="text" name='TournamentEndDate'
        [(ngModel)]="tourDetails.TournamentEndDate"  autocomplete='off' [bsConfig]="{ dateInputFormat: 'DD-MM-YYYY' }"
        [outsideClick]="true" [minDate]='tourDetails.TournamentStartDate'
         formControlName="TournamentEndDate" [ngClass]="{'form-submitted': formSubmitted}" required>
    <span *ngIf="form.get('TournamentEndDate').hasError('required')">Please fill out this mandatory field
    </span>

    </div>

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

Error Handling in Angular2 Http Service

Currently experimenting with the angular2 http module. Take a look at this angular component that performs a GET request: import {Component} from '@angular/core'; import {Http} from '@angular/http'; @Component({ selector: 'fou ...

The dropdown arrow icon fails to display downward direction when double-clicked

I'm working on a select dropdown that resembles a material UI dropdown. I've added icons for an arrow up and arrow down to indicate the state of the dropdown. The aim is to show the arrow up when the dropdown is open and switch to the arrow down ...

Stop Wordpress from automatically preloading html5 videos

I have a WordPress page containing numerous videos and I am looking to prevent them from preloading using HTML5. The challenge is that I am inserting the videos through the featured media options, which means I cannot directly add the preload="none" attrib ...

Do not apply hover effect to a particular child div when the hover effect is already applied to the parent

I am encountering a problem with the hover effect. I have 3 child div's structured as follows: <div class="parent"> <div class="child1">A</div> <div class="child2">B</div> <div class="child3">C</div ...

Unable to deploy Cloud Functions - missing .json file

Encountering deployment issues due to importing a .json credential file for functions. During the initialization of Firebase functions, I opted for TypeScript. Subsequently, after configuring my functions in TypeScript, I attempted to import the .json ...

Is there a way to move the submit form button to the next line using CSS?

I am having trouble centering the submit button below two input fields in a simple React form. Can anyone offer assistance with this? HTML .SearchBar-fields { display: flex; justify-content: center; margin-bottom: 2.88rem; flex-direction: row; ...

Displaying image behind bootstrap modal using Lightgallery js

Can anyone help me with an issue I'm having with previewing images using lightgallery js? The image is showing up behind the modal window. https://i.sstatic.net/FncZB.png I'm not sure why this is happening Here's the javascript code I am ...

The function Observable<string>.switchMap is not available

Currently, I am in the process of upgrading an application from Angular 4 to Angular 5. The following code snippet is found within a service: loadRefData(): Observable<RefData> { return this.participant$.switchMap((role) => { return thi ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

Convert the HTML content into a PDF while retaining the CSS styles using either JavaScript or Django

Looking to create a PDF of an HTML element with background color and images. Seeking a solution, either client-side or server-side using Django/Python. Tried jsPDF on the client side, but it does not support CSS. Considering ReportLab for Django, but uns ...

Library with integrated Jquery functionalities

Hello again with another query. I recently came across a jQuery code that allows you to click on an entire table row (tr) to show/hide other rows (specified as .none). I managed to find the code and it works perfectly on JSFiddle. However, when I try to im ...

How to insert a page break within a <table> element in a React application

Essentially, my table consists of several sub-headers and I need to insert a page break after a certain number of these subsections while avoiding automatic breaks within the sections. It should appear like this rough layout. The gray areas represent the s ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

What is the best way to selectively delete elements in d3.js?

I am faced with the task of manipulating a graph. I begin by opening and processing a file to extract the necessary modifications for the graph. These modifications are essentially node names stored within the text field of each node. My challenge lies in ...

Verifying if properties are empty in an array of objects

I am trying to find out if there is a null value in an array of objects, and return true if there is. One issue I am facing is: The current condition always returns 'false' due to the mismatch between types '{ type: any; startDate: string; ...

How to eliminate the validation icon from a select tag in Bootstrap 5?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c57505751425363160d110d11" ...

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

Why is my link not being acknowledged by its parent <div>?

I am facing an issue where a <a> tag inside a <div> element is not being recognized properly, causing the <div> height to remain unchanged and not accommodate the link as intended. You can view my HTML/CSS code here: http://jsfiddle.net/ ...

Encountering an i18next-fetch-backend issue during the transition to Angular 11

https://i.sstatic.net/TwrBx.png Encountering problems after upgrading to Angular 11 with the i18next-fetch-backend package's index.d.ts file. How can I troubleshoot this issue and what steps should I take to resolve it? Here is a snippet from the in ...

Exploring the world of using Bootstrap containers, rows, and columns

I have a good grasp on containers and columns, but I am a bit confused about rows. The example below shows a 50/50 split. <div class="container"> <div class="row"> <div class="col-md-6"> 50 / 50 Content </ ...