Can dynamic values be sent to a custom form validator in Angular 6?

Essentially, I am facing a challenge with validating form inputs that are interdependent (for example, ensuring that the "from" time is earlier than the "to" time). However, I'm unsure of the best approach to tackle this issue.

Below is my form group setup:

this.form = this.fb.group({
  fromTime: ["", [Validators.required, CustomValidator.myValidationFunction(this.form.get("toTime").value)]],
  toTime: ["", [Validators.required]]
});

Here is the current state of my custom validator:

static myValidationFunction(testing) {
    const toTime = testing; // set only once
    return control => {
      return toTime /*this value remains constant*/  ? null : { test: {} };
    };
  }

It appears that the value x or toTime is initialized only during the creation of the validator. Is there a method to pass dynamic inputs to a custom validator?

While I have reviewed Angular's documentation on custom form validation, I have been unable to find a solution to my particular issue.

Answer №1

function validateTime(formGroup) {
    const startingTime = formGroup.controls.startingTime;
    const endingTime = formGroup.controls.endingTime;

    if (startingTime.value && endingTime.value) {
        if (endingTime.value <= startingTime.value) {
            return {time: true};
        }

    }
    return null;
}

ngOnInit(): void {
    this.form = new FormGroup({
        startingTime: new FormControl('', Validators.required),
        endingTime: new FormControl('', Validators.required)
    }, validateTime);

    this.form.controls.startingTime.setValue(2);
    this.form.controls.endingTime.setValue(1);
}

To check in HTML:

{{form.hasError('time')}}

If you have any questions, feel free to ask.

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

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Exploring Custom Scrolling Effects in Angular 2

Have you ever heard of react-router-scroll in React? It allows React app pages to scroll smoothly like a regular website. The feature scrolls to the top of each new page (route), while remembering the scroll position of previous pages. This means that when ...

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Ways to obtain the component reference when clicking in Angular 2?

<!--snippet from template file--> <custom-element ... other attributes (click)="handleClick()" </custom-element> @Component({ //selector and templateUrl }) class MainComponent{ handleClick(){ // Obtaining the re ...

Angular 17 presents a unique challenge regarding APP_INITIALIZER and Server-Side Rendering (

Hello everyone, I've run into an issue while attempting to transition to SSR in Angular 17 from my current client-only setup in Angular 16. I have two services in play - CiyuanEnvironmentService and LiveService. The LiveService relies on the environme ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

Overriding TypeScript types generated from the GraphQL schema

Currently, I am utilizing the graphql-code-generator to automatically generate TypeScript types from my GraphQL schema. Within GraphQL, it is possible to define custom scalar types that result in specific type mappings, as seen below in the following code ...

Guide on utilizing TypeScript declarations imported as `* as`

Currently, I am working with react-icons and attempting to import all icon definitions using the syntax import * as Icons from 'react-icons/fi'. However, I am facing a dilemma on how to create a type that must be one of the types exported from Ic ...

The dimensions of the d3 div remain constant despite any modifications to its attributes

In my angular application, I am trying to customize the width and height of div elements in d3 when I select a legend. Strangely, I am able to adjust the width and height of the svg element without any issues. Here is the issue illustrated: https://i.ssta ...

Angular's DomSanitizer not functioning properly with the Transform css property

I have a question regarding my use of DomSanitizer. The background css property seems to be working fine, but the transform property is not displaying any output. I'm unsure where I might be going wrong in my implementation. In my Angular 8 code: i ...

NGRX 8 reducer now outputting an Object rather than an Array

I am facing an issue where the data returned from the reducer is an object instead of an array. Despite trying to return action.recentSearches, it doesn't seem to work as expected. The data being returned looks like this: { "loading": false, "recent ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Efficiently managing various, yet closely related routes in Angular

Is it possible to have the following link item be active for multiple links? <li class="nav-item"> <a class="nav-link" routerLinkActive="active" [routerLink]="['/testGame/list']"><i class="icon-game-controller"></i&g ...

Transform a nested AngularJS service into an Angular Observable service

Currently, I am working on migrating AngularJS(pre 1.5) services that use nested calls to a project being rebuilt in Angular(11). The challenge I'm facing is how to rewrite these services using RXJS. I have been searching for resources or detailed ex ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...