1

我是 React JS 新手,如何在 React JS 中实现两个日期字段之间的验证。

例如:结束日期应该只允许根据开始日期在 3 年内选择。

class MyForm extends React.Component {
    constructor(props) {
      super(props);
      this.state = { startdate: '', enddate: '' };
    }
    mySubmitHandler = (event) => {
      event.preventDefault();
      alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
    }
    myChangeHandler = (event) => {
      this.setState({startdate: event.target.value});
    }
    myEndDate = (event) => {
        this.setState({enddate: event.target.value});
      }
    render() {
      return (
        <form onSubmit={this.mySubmitHandler}>
        <img src="is.jpg"></img>
        <h2>Please select the Date range of .CSV </h2>
        <input
          type='date'
          onChange={this.myChangeHandler}
        />
        <span>   </span>
       <input
          type="date"
          onChange={this.myEndDate}
        />
        <h6 id="light">Note: Only up to 3 years worth of Data can be downloaded</h6>
        <div>
        {this.state.startdate && this.state.enddate && <input
      type='submit' value="Download" class="bi bi-cloud-arrow-down"  style={{ width: '10%', height: 30}}
    />}
        </div>
        </form>
      );
    }
  }
 
  ReactDOM.render(<MyForm />, document.getElementById('root'));

  export default MyForm;
4

1 回答 1

0
if (startDate) {
    var maxDate = startDate;
    maxDate = format(addMonths(startDate, 36), " E MMM dd yyyy HH:mm:ss ");
    var strToDate = new Date(maxDate);
    console.log("maxDate value ==" + maxDate);
  }

结束日期将从开始日期开始增加36个月,然后用户可以在该期间内选择。

然后将字符串转换为日期格式,然后将strToDate用于 datepicker 标记。

<DatePicker id="endDate-css" placeholderText={END_DATE} dateFormat='dd-MM-yyyy' selected={endDate} minDate={startDate} maxDate={strToDate} onChange={handleEndDate}/>
于 2021-06-22T09:47:57.423 回答