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

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the ...

The data received from the frontend is being replicated in the backend, causing duplication issues in a React

Whenever I click the button labeled onClick, it triggers the transmission of data (both time and ID) to the backend. The issue at hand is that the backend seems to be receiving the data twice instead of just once. On inspecting req.body, it becomes eviden ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Data structure for Highcharts:

Recently, I've been experimenting with Highcharts (http://www.highcharts.com) in a test application built on rails 3.1.1 and HAML. As someone who is still new to JavaScript, I'm striving towards achieving a seamless integration of Highcharts. Wi ...

Issue with Firefox mobile's camera functionality

I am facing an issue with my web app for mobile devices where I am trying to display the mobile camera using Firefox mobile browser. I am using nodejs with express as a server and connecting to the server via localhost with my smartphone. Although Firefox ...

Cross-origin resource sharing problem (Backend developed in Express, Frontend in Angular)

I am currently utilizing Angular for my front-end development and Express for the back-end. I encountered a CORS issue with one of multiple API endpoints that have similar configurations: Failed to load http://localhost:3000/api/deletePost: No 'Acc ...

Tips for accessing an API and setting up data mapping for a data table in nuxt.js

I desperately need assistance. I have been struggling with this issue for a while now, but all my attempts have ended in failure. My objective is to retrieve API data that corresponds to an array containing name, id, and email, and then display this inform ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Ways to Fix the React Hydration Issue in Next.js

I have been encountering an issue with the error message "Hydration failed because the initial UI does not match what was rendered on the server." I am unsure of what is causing this error and would appreciate any insights or suggestions from others who ma ...

How come the date displays as 21/1/2015 instead of 21/1/2015 in Android after parsing the JSON data?

Currently, I am utilizing the DatePicker functionality in my code and transmitting the value via JSON. The desired format for the value is 21/1/2015 without the extra backslashes. How can I resolve this issue? DatePickerDialog.OnDateSetListener date = n ...

how to change the color of a specific item in a list created using v-for

I'm a beginner when it comes to vueJs and I'm attempting to toggle the class "active" on a single element once it has been clicked. Currently, my code toggles all elements with the class material_icons. How can I modify it to toggle only the elem ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

Invoke a function from a neighboring component using React hooks

Is there a way to call a function from another component using props or context? I've attempted to do this using props and context, but I'm getting confused as I need to pass an actual function with parameters. The goal is to invoke the handleS ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

While attempting to scrape data, the console.log function displays the information, however it is not being returned

This code is now working perfectly! However, I am struggling to organize the data into an array of separate objects. getGAS: function(url) { var self=this; rp(options) .then(($) => { let gasset = []; $('.stations-list').each(functio ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...