[英]how do I set the min and max date for date fields?
我正在使用 React JS 和 Bootstrap 開發開始日期和結束日期字段屏幕,現在我需要為結束日期字段添加驗證。 例如:開始日期 01/01/2021 結束日期應該允許 select 從 01/01/2021(開始日期)到 3 年(01/01/2023)。
如果我使用datepicker我可以使用 min 和 max 屬性,但使用引導日期<Form.Control type="date" name="endDate" placeholder="endDate" onChange={this.endDatemyChangeHandler}/>
沒有這些屬性.
a)如何實現最小和最大屬性?
b)我正在使用placeholder="endDate"
但在 UI 中仍顯示dd/mm/yyyy而不是endDate
c)是否可以啟用日期字段從鍵盤輸入日期?
下面是我的完整代碼
import React from 'react'
import { Form } from 'react-bootstrap';
import './download.css';
import "./App.css";
class BootstrapDate extends React.Component{
constructor(props) {
super(props);
this.state = { startDate: '' };
}
myChangeHandler = (event) => {
this.setState({startDate: event.target.value});
}
endDatemyChangeHandler = (event) => {
this.setState({endDate: event.target.value});
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting "+"startDate==" + this.state.startDate +"endDate=="+ this.state.endDate);
}
render(){
return(
<div id="container">
<link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></link>
<img src="\is.jpg" id="ui-image"></img>
<div className="row">
<div className="col-md-4">
<Form.Group controlId="startDate">
<Form.Control type="date" name="startDate" placeholder="startDate" onChange={this.myChangeHandler}/>
</Form.Group>
</div>
<div className="col-md-4">
<Form.Group controlId="endDate">
<Form.Control type="date" name="endDate" placeholder="endDate" onChange={this.endDatemyChangeHandler}/>
</Form.Group>
</div>
</div>
<p id="note_bootstrap">Note: Only up to 3 years worth of Data can be downloaded</p>
<div>
{ this.state.startDate && this.state.endDate &&
<button id="button_bootsrap" onClick={this.mySubmitHandler} variant="primary" className="fa fa-download" >Download</button>
}
</div>
</div>
)
}
}
export default BootstrapDate;
首先,我一般使用功能組件和框架的“React Boostrap 組件”,所以我的答案將來自該上下文。
對於 A 和 B:
如果我有一個日期 object 我會像這樣預處理 object:
// date parameter is a date object
const setDate = (date) => {
// first convert date object to string
let date_as_string = date.toString();
// split the string and get the date part
let date = date.split("T")[0];
// return the date string
return date;
}
我會在 Controller 的 Boostrap 中插入這樣的變量。 此日期選擇器已從變量設置默認值,並且最大日期設置為當前日期。
<Form.Control
type="date"
max={new Date().toISOString().split("T")[0]}
defaultValue={setToday(date_variable)}
/>
PS:如果用戶輸入超過最大日期,我還會添加一個帶有 function 的 onBlur 或 onChange 屬性,該屬性將更改為當前日期。
C :我沒有任何好的答案,因為我沒有遇到 datepicker 的鍵盤輸入問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.