【问题标题】:How validate Date of Birth in react js如何在反应js中验证出生日期
【发布时间】:2021-05-10 13:35:39
【问题描述】:

我有一堆表单,我在 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>
                            
        </>);

【问题讨论】:

  • 我认为您粘贴的代码比生日有更多问题。您有必须首先修复的语法错误。然后不要忘记birthDate 应该是一个数字,而不是一个字符串。
  • 好的……

标签: reactjs


【解决方案1】:

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

【讨论】:

  • 您能详细说明您面临的问题吗?
猜你喜欢
  • 2022-07-29
  • 2019-02-27
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多