The error message is failing to display the mat error

I've implemented the Mat control date range input control in my project and I'm facing an issue regarding displaying an error message when the user forgets to enter either the start date or end date.

Below is the HTML code:

<mat-form-field>
<mat-date-range-input [rangePicker]="pickerDate" disabled="this.form.controls[isCurrentDateChange].value==='False'">
<input formControlName="startDate" matStartDate matInput placeholder="Start date"/>
<input formControlName="endDate" matEndDate matInput placeholder="End date" />
</mat-date-range-input>
<mat-error *ngIf="this.form.controls['endDate'].value=='null'">
Please enter date.</mat-error>
<mat-datepicker-toggle matsuffix [for]="pickerDate"></mat-datepicker-toggle>
<mat-date-range-picker #pickerDate><mat-date-range-picker>
</mat-form-field>

And here is the TypeScript code:

    export class MyComponent implements OnInit{
    form:FormGroup;
    constructor()
    {
    this.form=new FormGroup({
    startDate:new FormControl(null,[Validators.required]),
    endDate:new FormControl(null,[Validators.required])
    
    });
    
    saveForm()
    {
    let editForm=this.form.value;
      if(this.editForm.startDate==null)
      {
        this.editForm.controls['startDate'].markAsTouched();
        return false;
      }
      else if(this.editForm.endDate==null)
      { 
        this.editForm.controls['endDate'].markAsTouched();
        return false;
      }
     else
    {  
     return true;
    }
   }
 }

I have attempted various methods to display the error on the UI when the Save button is clicked, but it does not seem to be working. If anyone has any suggestions on how to show the mat error on the UI, please let me know. I have tried using ngIf as true, but the error is still not showing. Any help would be appreciated.

Answer №1

Starting from this point:

<mat-error *ngIf="this.form.controls['endDate'].value=='null'">

The comparison being made is to check if the value of endDate is exactly equal to the string 'null'. As a result, the <mat-error> will not display when there is no input in the endDate field.


Resolution 1

To verify if the value of endDate is null:

<mat-error *ngIf="!this.form.controls['endDate'].value">
  Please enter a date.
</mat-error>

Resolution 2

If you have used Validators.required in your form control, you can handle the validation error like this:

<mat-error *ngIf="this.form.controls['endDate'].errors?.required">
  Please enter a date.
</mat-error>

See Demo on StackBlitz

Note: There seem to be multiple errors in your provided code snippet. It's advisable to test your code thoroughly before asking questions to assist with debugging.

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

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

What is the best way to implement the <b-pagination-nav> component in Bootstrap Vue?

I'm eager to begin using the featured in this guide. However, I'm struggling to figure out how to incorporate the tag into my website. The tutorial's instructions are unclear and as a newcomer, I'm finding it difficult to make it func ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Utilizing Node.js to create a REST API that allows for seamless communication with a MongoDB database through

Currently, I am developing a web application utilizing the MERN framework (MongoDB, Express, Node.js for back-end, React for front-end). One specific part of my web application requires frequent access to a collection in the MongoDB database (every 50 ms) ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Remove information using Axios in ReactJS by interacting with an API

I have successfully pulled data from the jsonplaceholder API and stored it in my state. However, I am struggling with implementing the deleteContact() method to remove the data. Can anyone provide guidance on how to properly execute the deleteContact() met ...

Top method for transforming an array into an object

What is the optimal method for transforming the following array using JavaScript: const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; into this object structure: const result = ...

Utilizing dynamic routes and incorporating additional search parameters within the URL structure in NextJS has never

Is there a way to use router.push(url); to redirect a user with a URL structure like this: [:lang]/something/[...dynamicRouteParams]?searchParam=true. The problem I'm facing is that the user ends up being redirected to a page with a URL structure lik ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

Postback does not reload all controls in the NameValueCollection

Recently, I designed a custom User Control in asp.net. public class InputMask : CompositeControl, IPostBackDataHandler, IPostBackEventHandler Imagine the custom control is enclosed within a div element: <div runat="server" id="inputArea"> < ...

Using Mootools to call a class function from a bound CSS class may lead to an error stating that it is not a function

Utilizing Mootools 1.3.2 Here is the code snippet: var DNReportAbuse = new Class({ Extends: DNUserDialog, comment_id: null, container: null, initialize: function(classname) { var bindclass = $(document.body).getElements(classname); bindclass. ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

An error has occurred: Unable to access the property "filter" as it is undefined

After deploying my react-app online using npm run build, I encountered an issue where a page on my app displayed an error in Container.js. Despite being unfamiliar with this file and its purpose, I attempted to resolve the issue by reinstalling all node_mo ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...

Unpacking JSON and extracting a value in C#

// Extracting the JSON response. string content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); var rsJson = Newtonsoft.Json.Linq.JToken.Parse(content); Result result = ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Why does e.target.value only capture the initial letter of a string input in ReactJS?

Is the current method correctly capturing only the first letter in the string input? class Example extends React.Component{ state={ name:'Ajith' } changeEvent = (e) => { console.log('change : '+this.s ...