Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges.

The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are no visible errors, and the form continues to be deemed valid. I've experimented with making various modifications to this code, but without any success.

Any suggestions on what steps to take next?


Html:

<div class="alert-danger" *ngIf="form.controls.creditCheckDate.errors?.dateRange">
    Date should be from 1/1/2000 to Today.
</div>

.ts:

const controlsConfig = {
    creditCheckDate: ['', [Validators.required,
                           CustomValidators.dateRange(new Date(2000, 1), new Date(Date.now()))]]
};

return this.fb.group(controlsConfig);

Validator:

static dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
    return (c: AbstractControl): ValidationErrors | null => {
        const validationError = { dateRange: true };

        if (!c.value) {
            return null;
        }

        const timestamp = Date.parse(c.value);
        if (isNaN(timestamp)) {
            return validationError;
        }

        const date = new Date(timestamp);
        if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
        }

        return null;
    };
}

Answer №1

Please review the code below.

HTML

<form [formGroup]="testForm">
  <div class="row">
    <div class="col-xs-12 col-12 col-md-4 form-group">
      <input
        type="text"
        placeholder="Datepicker"
        class="form-control"
        bsDatepicker
        formControlName = "date"
      />
    </div>
    <div *ngIf="testForm.controls.date.invalid && (submitted)" class="text-danger">
        <small *ngIf="testForm.controls.date.errors?.required">
           Date is required
         </small>
       <small *ngIf="testForm.controls.date.errors?.dateRange">
         Date is invalid
       </small>
     </div>
  </div>
  <button type="button" (click)="onSubmit()">Submit</button>
</form>

TS

 import { Component } from "@angular/core";
    import {
      AbstractControl,
      FormGroup,
      FormControl,
      ValidationErrors,
      ValidatorFn,
      Validators
    } from "@angular/forms";
    
    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      testForm: FormGroup;
      submitted: boolean;
    
      constructor() {
        this.testForm = new FormGroup({
          date: new FormControl("", [Validators.required, this.dateRange(new Date(2000, 1), new Date(Date.now()))])
        });
        this.submitted = false;
      }
    
      dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
        return (c: AbstractControl): ValidationErrors | null => {
          const validationError = { dateRange: true };
    
          if (!c.value) {
            return null;
          }
    
          const timestamp = Date.parse(c.value);
          if (isNaN(timestamp)) {
            return validationError;
          }
    
          const date = new Date(timestamp);
          if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
          }
    
          return null;
        };
      }
    
      onSubmit() {
        this.submitted = true;
        console.log(this.testForm);
      }
    }

I tested the code in a code sandbox environment and it appears to be working correctly. https://codesandbox.io/s/suspicious-http-11288

Answer №2

After realizing that I had left out some crucial information, it became clear that the problem stemmed from someone resetting all errors for the form within a different validator. This method of handling things proved to be quite inefficient, causing me to struggle in identifying the issue for an extended period of time. However, once I finally discovered and rectified the issue, everything began to function as intended.

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

Filter the array while maintaining its current structure

I'm struggling to create an array filter that can handle exact and partial data within a nested array structure. The challenge is maintaining the integrity of the top-level structure while filtering based on data in the second layer. Here's an ex ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

I desire to obtain an image from a different webpage

I am a beginner in the world of Ionic/Angular. On my edit profile page (which is a separate page), I have the ability to change my profile picture. When I make this change, it should automatically reflect on my main profile page, which is on another page. ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Exploring the Yahoo Finance Websocket with Angular

Upon visiting the Yahoo finance website (for example, ), I noticed that the page establishes a WebSocket connection. The URL for this WebSocket is wss://streamer.finance.yahoo.com/ I'm currently working on a small project where I need to retrieve dat ...

Tips for embedding text into a doughnut chart with primeng/chart.js

Currently tackling a primeng chart project involving the development of a doughnut chart within angular. The task at hand is to display text inside the doughnut chart, aligning with the designated design vision. Referencing the image below for visualizatio ...

The Angular2 app and NodeJs in the Docker container are unresponsive

After creating a new Angular2 app using angular-cli and running it in Docker, I encountered an issue where I could not connect to it from localhost. First, I initialized the app on my local machine: ng new project && cd project && "put m ...

Tips on overcoming errors while attempting to create a copy of an object using Spread, especially when the object's class contains abstract methods

In the code snippet below, there is an abstract class that requires extended classes to implement a specific method. However, when utilizing the "spread" syntax, an error occurs due to the missing implementation of the abstract method. abstract class Test ...

I am encountering an issue where the object I am sending with Next.js is appearing as undefined on the receiving page

When transferring data from my question screen to a result screen, I am using an object called footprintsData. Here is the code snippet for sending the data: const footprintsData = { carFootprint: roundedCarFootprint, electricityFootprint: roundedElect ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

Error message: "Supabase connection is returning an undefined value

I am encountering an issue with my Vercel deployed Remix project that utilizes Supabase on the backend, Postgresql, and Prisma as the ORM. Despite setting up connection pooling and a direct connection to Supabase, I keep receiving the following error whene ...

Remove the color options from the Material UI theme

Can certain color types be excluded from the MUI palette in MUI v5? For example, can background and error colors be removed, allowing only colors defined in a custom theme file to be used? I attempted using 'never' but it did not provide a solut ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...

In TypeScript, the 'as const' syntax results in a syntax error due to the missing semicolon

I incorporated the following code into my react project: export const animation = { WAVES: "waves", PULSE: "pulse", } as const; export type Animation = typeof animation[keyof typeof animation]; Upon running the project, I encounte ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

The Angular Compiler was identified, however it turned out to be an incorrect class instance

Although this question has been asked before, I have exhausted all possible solutions that were suggested. Unfortunately, I still cannot resolve it on my own. Any assistance would be greatly appreciated. Error: ERROR in ./src/main.ts Module build failed: ...

Effective Strategies for Managing Real-Time Messaging in a MEAN Stack Application

I'm looking to create a MEAN Stack application, but I'm struggling to find clear guidance on how to implement live messaging similar to applications like WhatsApp or Facebook Messenger. At first, I considered using the setTimeout function and ma ...

The Angular application has encountered a stack overflow due to exceeding the maximum

./src/main.ts - An issue occurred: The module build process failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js): Error: Maximum call stack size exceeded import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; { App ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...

Deactivating the drag feature when setting the duration of a new event in FullCalendar

Hello there! I've integrated full calendar into my Angular project and I'm facing a challenge. I want to restrict users from defining the duration of an event by holding click on an empty schedule in the weekly calendar, where each date interval ...