Ashish Maidankar
Ashish Maidankar

Reputation: 21

How validate Date of Birth in react js

i have a bunch of forms where i make several validations for each field of form in react js, but now i want to validate a date of birth for 18+ restriction. i went through a lot a searching on internet but i did not found any satisfactory solution. i use input field type "date" for "dob" field. and now i dont know how to do it please help.

code.:-

class Dob extends Component {
    constructor(props) {
            super(props);
            this.state = {
             birthDate:"",
};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
}

  handleChange(event) {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  }

   handleSubmit(event) {
    event.preventDefault();
    }
 
 render() { 
        
        return ( <>
                         <Form onSubmit={this.handleSubmit}>
                            <Form.Group as={Col}>
                            <Form.Label id="formLabel">Date Of Birth</Form.Label><br/>
                            <Form.Control type="date"                                   
                                    name="birthDate" 
                                    placeholder="Enter Your Birthdate"
                                    value={this.state.birthDate}
                                    onChange={this.handleChange}
                                   />  
</Form.Control>
</Form>
                            
        </>);

Upvotes: 0

Views: 5116

Answers (1)

noob_nerd
noob_nerd

Reputation: 551

Let us say the user has entered birth-date as "20-01-2021".

var bday="20-01-2021";
bday=bday.split("-");
var bday_in_milliseconds = new Date(parseInt(bday[2], 10), parseInt(bday[1], 10) - 1 , parseInt(bday[0]), 10).getTime(); //birth-date in milliseconds
var now = new Date().getTime(); //current time in milliseconds
if(now - bday_in_milliseconds > 567648000000){ //567648000000 is 18 years in milliseconds
    // 18+
}
else{
    // under 18
}

Upvotes: 2

Related Questions