Tips on validating the start and end dates in an Angular Formly form

In my Angular 8 project, I have two input fields for the start date and end date. I want to ensure that the end date is always equal to or greater than the start date.

I am utilizing both Angular 8 and ng module in my development process.

I've extracted data from myfile.json to create the text fields and used my custom date validation function (validation.ts) within the HTML formly code.

As a beginner Angular developer, I am seeking assistance on validating these two dates effectively.

json code
{
              "className": "col-md-6 col-xs-12",
              "key": "graduationstartdate",
              "type": "input",
              "templateOptions": {
                "label": "Course start Date",
                  "appearance": "outline"

              }
            },

            {
              "className": "col-md-6 col-xs-12",
              "key": "graduationenddate",
              "type": "input",
              "templateOptions": {
                "label": "Course End Date",
                "appearance": "outline"
              }
validation.ts
it contains a function to validate the date
form.html
contains formly code of form

Answer №1

To effectively reach your goal, I recommend utilizing reactive forms. This involves creating a formGroup to contain all form controls and implementing a custom validator to apply to your form. For more information on how to use custom validators, please refer to the documentation: https://angular.io/guide/form-validation-custom

Answer №2

If you're looking for a way to implement a date picker in Angular, consider using the Angular Material date picker component.

Check out the examples here

Specifically, navigate to the section titled:

Datepicker with min & max validation

In this section, you'll find instructions on how to add a Datepicker with minimum and maximum validation.

Alternatively, you can create a custom validator that ensures the end date is not earlier than the start date:

constructor(private formBuilder: FormBuilder) { 
  this.formGroup= this.formBuilder.group({
    startDate: [''],
    endDate: ['']
  }, {validator: this.checkDates});  
}

If you need to update the values of your form controls later on, use patchValue or setValue method:

this.formGroup.setValue({
  startDate: this.formGorup.startDate;
  endDate: this.formGroup.endDate;
})

The custom validator enforces that the end date comes after the start date, returning a validation error if necessary:

checkDates(group: FormGroup) {
  if(group.controls.endDate.value < group.controls.startDate.value) {
    return { notValid:true }
  }
  return null;
}

To display this custom error message in your template, add the following code:

<small *ngIf="formGroup.hasError('notValid')">Not valid</small>

Don't forget to include the formGroup within your form tag:

<form [formGroup]="formGroup">

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

Obtain Python script output displayed in HTML format

I am currently working on developing Python scripts that can be utilized by front-end HTML+CSS developers for websites. To test the feasibility of this approach, I have written a basic script that makes use of parse.com as the backend. The script retrieves ...

tsc is not able to identify virtual fields in a mongoose schema

I'm having trouble getting mongoose virtual to work in typescript. Following the instructions outlined in "another approach" on mongoose documentation, I used mongoose's InferSchemaType to create the interface. However, TSC does not recognize t ...

Creating a bundle in Symfony 3 consistently prompts the message "Make changes to the composer.json file."

Hey there, I've been diving into the world of symfony and encountering a frustrating issue. Whenever I use the "php bin/console generate:bundle" command to create a bundle, even if I stick with all the default settings, an error keeps popping up: T ...

Learn how to navigate to a different page in Angular 4 using a button click

I'm trying to set up a button in my home.component.html page that will redirect the URL to a new page when clicked. My expectation is that clicking the button will change the current URL from http://localhost:24282/home to http://localhost:24282/mast ...

Implement foreach in Angular with the help of Concatmap

Issue: I am facing a challenge while attempting to make 3 HTTP post requests to 3 different endpoints using concatMap to sequentially HTTP post to an observable. The problem arises when I try to extract each value from the formarray using a foreach loop. ...

How to interact with Angular2 Material sidenav from a component

Is there a way to access the md-sidenav that is defined in *.component.html? My goal is to dynamically control its mode (over | push | side) based on properties like screen width. How can I retrieve the md-sidenav element below? <div class='layou ...

Using TypeScript to asynchronously combine multiple Promises with the await keyword

In my code, I have a variable that combines multiple promises using async/await and concatenates them into a single object const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([ _.zipObject( [&quo ...

WordPress REST API - Issue with New Category returning undefined, yet still able to be accessed

Currently, I am utilizing the WordPress REST API and have successfully created a new category. However, when making queries to the API, it is returning undefined for that particular category. Upon visiting: /wp-json/wp/v2/categories, category 17 does not ...

ngFor displaying an abundance of elements

I am retrieving data from a database and utilizing an ngFor loop to display it. Here is the HTML code snippet: <div style="background:black; color:aliceblue;" class="col-md-8 col-md-offset-2 text-center" [routerLink]="['todo']"> ...

The Angular routing feature causes the URL to display a forward slash

When attempting to retrieve the current router path using Router in my Angular application, I encountered a discrepancy. Despite being on "/login", the console.log(this.router.url) shows "/", whereas inspecting the entire this.router object reveals that th ...

Issue encountered while trying to connect with rest service via XMLHttpRequest in WebExtension

Currently, I'm attempting to connect to a rest service that is being hosted on an Amazon AWS server through a Firefox WebExtension. In my manifest.json file, I have included a background script that is responsible for accessing the service. "backgro ...

Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } As I was working on my applicat ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Using React with TypeScript to implement a nested map function

I have developed an application using React typescript, incorporating redux and saga for state management. The data fetched is displayed on the browser with Google Maps integration where hovering over properties displays them on the map. To enhance user ...

Escaping latitude and longitude coordinates using PHP

I am looking to include longitude and latitude values in a json file. However, the current code I have escapes the values and adds quotation marks. Example of json output{"votes":["{\"lat\":\"51.426799\",\"lng\":\"-0.331 ...

Using Chrome Developer Tool to extract information such as names, addresses, and phone numbers from directory sites like TruePeopleSearch.com

Hey everyone! I'm currently in the process of expanding my knowledge on data parsing using Python. Lately, I've been exploring how to use Chrome Developer Tools effectively. One thing that's got me stumped is figuring out how to copy or view ...

Unable to grasp the mistake

My code contains a function: buy() { return new Promise((resolve, reject) => { this.http.request('http://192.168.1.131:8888/generatetoken.php') .subscribe(res => { resolve(res.text()); }); }).then((key) => ...

I am in need of assistance with incorporating a particular hibernate Inheritance mapping into my project

I am dealing with a situation where I have two classes, parent and child, with a self-referential relationship on the child side. The database is set up with separate tables for both parent and child, sharing the same "id", and using the column "holder" as ...

Trouble with displaying cell content in ag-grid within an Angular application

I have implemented ag-grid in my Angular project and I am trying to redirect to a link when a specific cell is clicked. Currently, I have a new value coming from an API which is nested inside an object in an array. For example, the object is dto-> dat ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...