如何在react js中验证出生日期



我有一堆表单,其中我对react js中的每个表单字段进行了多次验证,但现在我想验证18+限制的出生日期。我在网上搜索了很多,但没有找到任何令人满意的解决方案。我使用输入字段类型";日期";对于";dob";领域现在我不知道该怎么做,请帮帮我。

代码:-

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>

</>);

假设用户已将出生日期输入为"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
}

最新更新