Using Angular2's formbuilder, validators, and testing to ensure that the end date is set to a value greater

I am facing a challenge with the start and enddate input tags in my HTML.

Utilizing Angular, FormBuilder, and custom Validators, I have implemented a validation system to ensure that both the start date and end date are valid.

Below is a snippet from my component showcasing the form group setup:

this.form = fb.group({
            startdate: ['',Validators.compose([Validators.required,ModelValidators.validStartDate])],
            enddate: ['',Validators.compose([Validators.required,ModelValidators.validEndDate])],

        });

Here are the custom validators I have created:

static validStartDate(control: Control){
        var valid: any;
        valid=null;
        var diff:any;
        diff = new Date(control.value).valueOf() - new Date('1999-01-01').valueOf();
        if (diff>=0){
            valid=true;
        }
        return valid ? null : { validStartDate: true };

    }

    static validEndDate(control: Control){
        var valid: any;
        valid=null;
        var diff:any;
        diff = new Date().valueOf() - new Date(control.value).valueOf();
        if (diff>3600*24){
            valid=true;
        }
        return valid ? null : { validEndDate: true };
    }

Now, the puzzle I need to solve is how to validate that the enddate is greater than the start date and also ensure that the difference between enddate and startdate is more than 1 year.

Is it feasible to pass additional data to the ModelValidators.validEndDate function? Any insights or suggestions on this matter would be greatly appreciated!

Answer №1

Follow these steps:

this.form = fb.group({
   startdate: ['',Validators.compose([Validators.required,ModelValidators.validStartDate])],
   enddate: ['',Validators.compose([Validators.required,ModelValidators.validEndDate])],
        },{validator: this.validateDates}));

Next, in your validator class, implement the following function

validateDates(group: ControlGroup) {
  var valid = false;

  for (name in group.controls) {
    var val = group.controls[name].value

    (...)
  }

  if (valid) {
    return null;
  }

  return {
    areEqual: true
  };
}

For more information, refer to this question

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 in parsing: An unexpected symbol appeared, an identifier or keyword was expected at the end of the expression

Whenever I attempt to display data from an API, an error always pops up. My goal is to showcase each piece of data individually. To help you analyze the issue, I've included the URL of the API below: civilizationes.component.ts import { Component, O ...

Converting a .ts file to .js for Typescript 3.2 and higher versions

Is there an alternative method to compile a .ts file to .js file using Typescript version 3.2 and above since tsc.exe is no longer present in these versions? In our project, we relied on tsc.exe to compile all the .ts files, but with the upgrade to Typesc ...

Encountering issues with the command npm install --save web-animations-js, the

Issue encountered while trying to run "npm install --save web-animations-js". It seems like the request to https://registry.npmjs.org/web-animations-js failed due to a mismatch in the Hostname/IP in the certificate. The error message indicates that the Hos ...

Access network path through browser using Angular

I'm having trouble opening a network path from my browser using the code below. The browser keeps throwing an error saying it's unable to load local resources. Can you please provide some advice on this issue? public openUrl() { window.o ...

Adding a text box dynamically to an Angular form upon clicking the Add button is currently not functional

I have created a basic angular form that should add text fields dynamically when the user clicks on a button. However, when I click the "Add" button, it does not add a new text box as expected. Can anyone help me figure out what I am missing? app-componen ...

angular - apply custom background styles without resorting to disabling ViewEncapsulation

I can't seem to figure out why I'm struggling to set the background of my component correctly without having to use ViewEncapsulation.None. Currently, with ViewEncapsulation.None, my styles look like this: * { margin: 0; padding: 0; ...

Ways to retrieve specific Observable elements?

Having a function like this: getCategories(): Observable<any> { return this.category.find({where: {clientId: this.userApi.getCurrentId()}}) }; The return type of this.category.find is Observable<T[]>. When I invoke g ...

Get the dynamic type as the return value in a TypeScript abstract class method with generic type T

Within my codebase, I have created an abstract class: export abstract class Filters<P> { protected field: string; protected constructor(field: string) { this.field = field; } protected abstract getFilter(): P; } Additionally, there is ...

Running Jasmine asynchronously in a SystemJS and TypeScript setup

I am currently executing Jasmine tests within a SystemJS and Typescript environment (essentially a plunk setup that is designed to be an Angular 2 testing platform). Jasmine is being deliberately utilized as a global library, rather than being imported vi ...

Manage the appearance of a component using props

Here is the code snippet that I am working with: export type BreadcrumbItemProps = { isCurrent?: boolean; }; const isCurrent = (props: { isCurrent?: boolean }) => props.isCurrent ? 'normal' : 'bold'; export const Item = styled.s ...

Using TypeScript with MongoDB aggregation

Recently, I've been working on a User model with the goal of achieving generic aggregation. Essentially, I want to be able to pass an array of objects to a function and have it execute smoothly. Let me provide you with a snippet of the getUser functi ...

Error in Angular2: The provided parameters do not match any of the available function signatures

I have implemented logic in the code snippet below to dynamically adjust rows and columns based on my specific business requirements. However, when I include this code in my Angular2 TypeScript file, I encounter an error stating that the supplied paramet ...

Form Control Date Mask with Material Picker

Having trouble using Angular 6 Material Date Picker with a mask from ngx-mask, angular2-mask, or angular2-text-mask and the formControlName attribute? If you're seeing this error message: ERROR Error: More than one custom value accessor matches for ...

The module `perf_hooks` could not be resolved

Trying to integrate perf_hooks library from the nodeJS Performance API into my React Native project has been quite a challenge. Here's the snippet of code I've been working with: import {performance} from 'perf_hooks'; export const mea ...

Angular 10 - Compilation errors caused by the element's location

When running 'ng serve' or 'ng build' in Angular 10, I encountered a build error that stated: ERROR in projects/project-navigator/src/app/modals/building-permissions.component.html:89:61 - error NG8002: Can't bind to 'ngClass& ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

Retrieving unique attributes from script tag (excluding data- prefix)

I am dealing with multiple sites that contain the following code snippets: <script async custom-element="amp-sidebar".... <script async custom-element="amp-slider".... My aim is to extract all the custom-element properties using vanilla JavaScript ...

Angular NX: Managing multiple libraries with identical names

Currently integrating Angular with NX, I have established two distinct groups: books and cars. My goal is to develop an overview library for each group that includes a table for viewing either books or cars. To start, I created the library under libs/book ...

The CSS variables set within the :root section of styles.scss are not recognized as valid

Trying to implement global colors using CSS variables in my Angular 11 app. The styles.scss file contains: :root{ --primary : #0b68e8; --secondary:#ABCFFF; } .test-class{ background: var(--primary); } However, when applying this class in one ...

Guide to generating a consistent 16:9 preview of a different html page

I'm currently developing a simple webpage editor that allows users to create "slides" for later display elsewhere. For this purpose, I have designed the following layout: The left section serves as a preview while the right section functions as the ...