I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/>

<input type="time" onChange={(e)=>setTime(e.target.value)} />

If the selected date is after today and the time is after the current time, display a validation message stating "Please select a previous time".

I would like to have validations for both the time and date inputs.

Answer №1

To successfully accomplish this task, you will need to instantiate a new Date object that captures the current date and time, and then compare it with the date and time selected.

Your react component should be structured as follows:

const [date, setDate] = useState("");
const [time, setTime] = useState("");
const [error, setError] = useState("");

const handleDateChange = (e) => {
  const selectedDate = new Date(e.target.value);
  const currentDate = new Date();
  if (selectedDate.setHours(0,0,0,0) < currentDate.setHours(0,0,0,0)) {
    setError("please select a previous time");
  } else {
    setDate(e.target.value);
    setError("");
  }
};

const handleTimeChange = (e) => {
  if (date) {
    const selectedDateTime = new Date(`${date}T${e.target.value}`);
    const currentDateTime = new Date();
    if (selectedDateTime.getTime() < currentDateTime.getTime()) {
      setError("please select a previous time");
    } else {
      setTime(e.target.value);
      setError("");
    }
  } else {
    setTime(e.target.value);
  }
};

// Within your render method
<input type="date" onChange={handleDateChange} />
<input type="time" onChange={handleTimeChange} />
{error && <p>{error}</p>}

Answer №2

To accomplish the previously mentioned goal, I would adopt this method:

import React, { useState } from 'react';

const DateTimeValidator = () => {

  const [date, setDate] = useState('');
  const [time, setTime] = useState('');
  const [validationMessage, setValidationMessage] = useState('');

  const handleDateChange = (e) => {
    setDate(e.target.value);
    validateDateTime(e.target.value, time);
  };

  const handleTimeChange = (e) => {
    setTime(e.target.value);
    validateDateTime(date, e.target.value);
  };

  const validateDateTime = (selectedDate, selectedTime) => {
    const currentDate = new Date();
    const selectedDateTime = new Date(`${selectedDate}T${selectedTime}`);

    if (selectedDate && selectedTime && selectedDateTime > currentDate) {
      setValidationMessage('Please select a past time.');
    } else {
      setValidationMessage('');
    }
  };

  return (
    <div>
      <input type="date" onChange={handleDateChange} />
      <input type="time" onChange={handleTimeChange} />
      {validationMessage && <small>{validationMessage}</small>}
    </div>
  );
};

export default DateTimeValidator;

Let's walk through the code provided above:

handleDateChange updates the date state and handleTimeChange updates the time state. Both functions then call validateDateTime to evaluate the selected date and time. The validateDateTime function constructs a Date object based on the chosen date and time inputs, compares them to the current date and time, and verifies whether they are in the future.

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

What caused Safari to only show half of the page?

Whenever I browse my website using Safari, I noticed that if the total size of the content on the first page is less than 100vh, Safari ends up cutting off half of the page. To fix this issue, I added a CSS rule in the body setting min-height to 110vh wh ...

Guide to saving a Python docx file on the client side with the help of Ajax

I am currently using Python 3.6 with Django, and my code snippet is shown below: from docx import Document document = Document() document.add_heading('My docx', 0) document.save('myFile.docx') return HttpResponse(document, content_typ ...

Encountering an issue with Angular routing: Cross-origin requests are restricted to specific protocol schemes, such as HTTP

I encountered an error while working on angular routing. Below is my HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src= ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

The specific type of selection return type in Prisma is restricted

My Prisma schema is structured like this: model Sample { id String @id @default(cuid()) createdOn DateTime @default(now()) category String } category should STRICTLY belong to one of these options: const Categories = [ "alphaC ...

What is the best method to verify image dimensions and size for three distinct target platforms, all of which have different image dimensions but the same size, within

I'm currently working on a feature that involves an image uploader for various platforms, each with its own set of recommended image dimensions. For example: platform 1 - dimension 920 x 300, platform 2 - 210 x 200, and platform 3 - 790 x 270. When th ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

Print directly without the need for a preview or dialog box

Is there a way to easily print content with just one click, without having to go through the preview or print dialog box? Here is a snippet of my code: <head> <style type="text/css"> #printable { display: none; } @media print { #non-pr ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...

Rendering components before ComponentDidMount runs and Axios handles state updates

When I try to pass the gifs state to my GifList component in the render method, I encounter an issue. It seems that when trying to access the array within the component through props, it is returning as undefined. After investigating further, I noticed t ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Struggling with integrating HTML Canvas within Vue.js

Currently, I am attempting to upload an image by utilizing HTML canvas. My decision to use canvas stems from the fact that I will be superimposing additional images based on the data received from the API, and this process seems more straightforward when u ...

ServiceAccountKey cannot be located by Firebase deploy

I am in the process of integrating a serviceAccountKey into my Typescript cloud functions project. var serviceAccount = require("/Users/kareldebedts/myAppName/functions/serviceAccountKeyName.json"); admin.initializeApp({ storageBucket: "appName.appspot ...

What is the method for identifying the selected radio button that has been dynamically generated after clicking the submit button?

Despite this question being asked multiple times before, I am struggling to find a solution that fits my specific scenario. Initially, I have a static radio button that I create. The HTML code is as follows: <body> &l ...

JavaScript Date displaying the string in the format YYYY/MM/DD HH:MM

I'm struggling to figure out how to format a date and time string like this: "YYYY-MM-DD-HH-MM" Can anyone help me with this? Here is the code I currently have: var x = new Date(); var formattedTimeStamp = x.toString(); Current Output: Tue Oct 3 ...

Unable to concatenate values from Object in JavaScript

Although it may seem trivial, the following code is giving me trouble: window.temp1.targetInterests It gives me back: Object {Famosos: "Famosos", Musica: "Música", Humor: "Humor"} I attempted to join it: window.temp1.targetInterests.join('/&apos ...

Even when autocomplete is disabled, Firefox continue to cache hidden input fields

I'm encountering an issue with a form that has the autocomplete attribute set to off. Within this form, there is a hidden input element (created using ASP.NET MVC's Html.HiddenFor() method): <input type="hidden" value="0" name="Status" id="S ...

Expanding Text Box

My goal is to create a textarea that automatically adjusts its size as the user types or pastes long text into it. This is my current implementation. class AutoResizeTextArea extends InputBase { render() { const { label, placeholder, wrap, ro ...