Skip to content

Commit

Permalink
fix: Allow typing in date widget (#1247)
Browse files Browse the repository at this point in the history
* Allow typing in date widget

* Handle empty case & warn user when invalid

* Try parsing date with moment

* Rename isValid -> isValidDate

* Warn user when date is invalid
  • Loading branch information
Dammmien authored and tech4him1 committed Apr 14, 2018
1 parent 3eb30e5 commit 9975c7e
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/components/EditorWidgets/Date/DateControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,37 @@ export default class DateControl extends React.Component {
}
}

// Date is valid if datetime is a moment or Date object otherwise it's a string.
// Handle the empty case, if the user wants to empty the field.
isValidDate = datetime => (moment.isMoment(datetime) || datetime instanceof Date || datetime === '');

handleChange = datetime => {
const { onChange } = this.props;
if (!this.format || datetime === '') {
onChange(datetime);
} else {

// Set the date only if the format is valid
if (this.isValidDate(datetime)) {
const formattedValue = moment(datetime).format(this.format);
onChange(formattedValue);
}
};

onBlur = datetime => {
const { setInactiveStyle, onChange } = this.props;

if (!this.isValidDate(datetime)) {
const parsedDate = moment(datetime);

if (parsedDate.isValid()) {
const formattedValue = parsedDate.format(this.format);
onChange(formattedValue);
} else {
window.alert('The date you entered is invalid.');
}
}

setInactiveStyle();
};

render() {
const { includeTime, value, classNameWrapper, setActiveStyle, setInactiveStyle } = this.props;
const format = this.format;
Expand All @@ -53,7 +74,7 @@ export default class DateControl extends React.Component {
value={moment(value, format)}
onChange={this.handleChange}
onFocus={setActiveStyle}
onBlur={setInactiveStyle}
onBlur={this.onBlur}
inputProps={{ className: classNameWrapper }}
/>
);
Expand Down

0 comments on commit 9975c7e

Please sign in to comment.