Hacker rocker1169
Hacker rocker1169

Reputation: 83

React code to display date in Formatted Way and limit future dates

In REact I am having a state variable like this

    const [ dob, setDob ] = useState();

and in the jsx I am having like this

<input type="date" max="new Date()" value = {dob} onChange={(e)=>setDov(e.target.value)}/>

I am facing two issues

  1. I am unable to limit future dates i.e all the dates after today cant be selected but when I am giving max attribute as I am unable to limit the future date
new Date() or new Date().getTime()
  1. I need to show the date after selection in this format DD/MM/YYYY I am unable to display the converted date.For it I tried modyifying the onChange() as onChange()=>setDob(new Date(e.target.value.tolocaleTimestring())) But still its not working. I am getting error toLocaleString() is not a function

Notes:- I am using React and purely functional components

Upvotes: 0

Views: 710

Answers (2)

pritam
pritam

Reputation: 2558

If you look at the MDN docs for date type and constraining the inputs, you can use min and max attributes on input. So what you did is right except passing a string to max. It needs to be a string (parsable to date) or date object I think.

e.g.

<input type="date" max={new Date()} value = {dob} onChange={(e)=>setDov(e.target.value)}/>

Refer - https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types#constraining_datetime_values for more details.

Upvotes: 1

Ghassan Maslamani
Ghassan Maslamani

Reputation: 809

You have multiple error/problem in the code:

1- You can't add JS code in html variable, the HTML max property accept texts. and another issue you had there (event if max accepts JS expression) is that new Date () dosen't match the format it accepts, you have to convert it ISO standard i.e. new Date().toISOString().

2- I am not sure whats the issue you are facing here, belwo I added a snippest that worked for me, that resolved both (1 and 2).

const [ dob, setDob ] = useState();
 const today = new Date().toISOString();
  return (
    <div >
   <input type="date" max={today} value = {dob} onChange={(e)=>setDob(e.target.value)}/>
    </div>
);

Upvotes: 0

Related Questions