The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group.

Within my code file, specifically the .ts file:


        form: FormGroup;

        constructor(
            private fb: FormBuilder,
            private validatorSrv: CustomValidatorService,
        ) {}

        createForm(): void {
            this.form = this.fb.group({ 
                trans_date: [null, [Validators.required, this.validatorSrv.validDate]] 
            });
        }
    

Now, focusing on the CustomValidatorService class:


        validDate(c: AbstractControl): any {
           // It always return 'Mon Jan 01 2001 00:00:00 GMT+0800 (Taipei Standard Time)' 
           // When value is 1
           // And 'Sat Dec 01 2001 00:00:00 GMT+0800 (Taipei Standard Time)'
           // When value is 12
           console.log(c.value); 
        }
    

In the scenario mentioned above, it consistently outputs a JavaScript datetime object.

Is there a way to extract the exact input value from the custom validator's AbstractControl?

Answer №1

It is a frequent occurrence. One solution is to change the date to a string within your validator.

If you are unaware, the Angular Material datepicker has compatibility with moment.js.

For your situation, utilizing this feature may be beneficial. By doing so, you could address your problem simply by converting your date using one of the various functions provided by moment.

Answer №2

It's always a challenge to decide on the best approach for custom date validation, especially when considering the common use of date objects over user input strings. While some may opt for an AbstractControl custom format validation, I find this method to be overly complex for my needs.

Instead, I prefer a more straightforward solution by implementing a simple function triggered on the keypress event of the control for validation purposes.

checkDateValidity(): boolean {
   // Omitted lengthy logic for brevity...
   if (format matches mm/dd/yyyy or mm-dd-yyyy) { return true; }
   return false;
}

handleDateValidation(e: any): void {
    const control = this.form.get('trans_date');

    if (this.checkDateValidity(e.target.value)) {
      control.setErrors(null);
    } else {
      control.setErrors({ invalidDate: true });
    }
}

The ability to programmatically assign errors to a ReactiveForm Control using the setErrors() method is truly remarkable.

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

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Angular - attaching functions before page navigation - incompatible with HostListener

I'm looking for a way to implement some logic in an angular component that runs before the user navigates away from the page. I've tried a few suggestions found through Google, but so far nothing has worked for me. One approach I attempted involv ...

In Angular 2+, what is the comparable counterpart to Vue's Vuex?

I have experience with Vue's Vuex, but I am currently working on an Angular application. I would like to implement a similar principle where all components are managed from one central location (like a store in Vue). Is there an alternative to Vuex in ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

Creating multiple rectangles and filling them with a color chosen by the user in Angular can be achieved by following these steps

Looking for advice on angular coding. I'm working on a project that requires creating multiple rectangles and filling them based on selected values. Can anyone suggest a module that would offer this functionality? ...

Dealing with errors using Javascript and Node.js (then/catch)

Suppose I have the following pseudocode in my routes.js file: var pkg = require('random-package'); app.post('/aroute', function(req, res) { pkg.impl_func(data, function (err, result) { myFunction(entity).then(user=>{ ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Attempt the HTTP request again only for specific status codes

When developing my Angular application, I encountered a situation where I needed to make an HTTP call to a backend server. To enhance its reliability, I decided to incorporate an interceptor to implement the retry pattern. In the past, I utilized RxJS&apo ...

Generating an assortment of specific rows by utilizing checkboxes in React JS

I'm currently dealing with a table of data where the first column consists of checkboxes. My goal is to generate an array containing the ID of each row that is selected. const [selectedRows, setSelectedRows] = useState([]); const handleCheckbox ...

"Encountering issues with ngrx store selector when importing app from a custom

My Angular library includes a store implementation and is distributed as an NPM package, used in various Angular applications. I encountered an error when attempting to use a ngrx store selector exported from the library in a different Angular project: ...

Is there a way to utilize a cookie in order for the website to recognize that I have already agreed to the terms?

It's common for websites to ask for cookie and privacy acceptance upon loading, especially in the EU. I'm looking for a way to automatically accept these cookies so I don't have to constantly click "accept all" every time I open Chrome. My ...

How can TypeScript limit the number of properties allowed to be passed as a function parameter?

Here is what I currently have: export interface RegionNode { nodeSelected: boolean; nodeEditable: boolean; zone: Partial<Zone>; parent: RegionNode | null; children: RegionNode[]; } Now, I am looking for a sleek solution to create ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

Is it possible to modify or delete the question mark in a URL?

Currently, I am working on implementing a search bar for one of my websites hosted on Github. Below is the code I have written for the search bar: <!-- HTML for SEARCH BAR --> <div id="header"> <form id="newsearch" method ...

activating javascript function in rails when the page reloads

I have a rails4 app and I'm looking to implement some specific JavaScript events when the page loads, but only if the user is coming from a certain page. On the post#index page, all comment replies are initially hidden. When a user clicks on a specif ...

I attempted to copy the "koa" module from my node_modules folder to a custom typeRoots directory, but it doesn

I want to use Ant Design UI, and I hope to import the script tag with the .min.js label, like this: <script src="//cdn.staticfile.org/react/15.4.1/react.min.js"></script> <script src="//cdn.staticfile.org/react/15.4.1/react-with-addons.min. ...

Extract the image source from this HTML retrieved using JavaScript

I need to retrieve the source URL of an image from a certain part of a document. Here is my current approach: var theImg = document.getElementById('imageDiv').innerHTML; The above code snippet returns something like this: theImg = <img src ...