0

I have successfully implemented the react js datepicker. Now I want to restrict users below 18 years to not register.

This is my datepicker

<DatePicker
 selected={this.state.dob}
 onChange={this.dateChange}
 className="form-control"
 maxDate={new Date()}
 />

Suggest me what to do. Thank You!

Karan Patokar
  • 465
  • 1
  • 8
  • 21
  • 1
    You can't restrict user. Users lie! – Takit Isy Apr 16 '18 at 17:32
  • Do you want to restrict it within the datepicker? Otherwise you can check it when user clicks to register. – Ali Ankarali Apr 16 '18 at 17:39
  • How do I do that @AliAnkarali – Karan Patokar Apr 16 '18 at 18:21
  • The answer in this question has the function to calculate age:https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd You can pass this.state.dob to that function on onSubmit of the form or onClick of the button and continue accordingly. – Ali Ankarali Apr 16 '18 at 18:25
  • In your change handler function do math to see if they're older or younger than 18. Hold a boolean in `this.state` that you set to control the `disabled` prop in the submission button. It'd also be helpful to show an error somewhere, which can controlled with the exact same variable – Andrew Apr 17 '18 at 02:19

1 Answers1

0

I have just added "this" to work in desired scope.
Modified code:

const ageRestriction = new Date().setFullYear(new Date().getFullYear()-18)
<DatePicker
selected = { this.state.dob }
onChange = { this.dateChange }
className = "form-control"
maxDate = { ageRestriction }
/>
Jeet
  • 1
  • 1