Skip to content

Commit 9b84006

Browse files
authored
fix(datepicker): Validating inserted date on Enter (#11)
1 parent b7b0028 commit 9b84006

File tree

3 files changed

+15
-12
lines changed

3 files changed

+15
-12
lines changed

src/components/datepicker.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,13 @@ class SemanticDatepicker extends React.Component {
289289
});
290290
};
291291

292+
handleKeyDown = evt => {
293+
// If the Enter key was pressed...
294+
if (evt.keyCode === 13) {
295+
this.handleBlur();
296+
}
297+
};
298+
292299
onDateSelected = (...args) => {
293300
if (this.isRangeInput) {
294301
this.handleRangeInput(...args);
@@ -321,6 +328,7 @@ class SemanticDatepicker extends React.Component {
321328
onChange={this.handleChange}
322329
onClear={this.resetState}
323330
onClick={this.showCalendar}
331+
onKeyDown={this.handleKeyDown}
324332
value={typedValue || selectedDateFormatted}
325333
/>
326334
{isVisible && (

src/utils.js

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,15 @@ export const parseFormatString = formatString =>
6262
formatString.replace(/[D, Y]/gi, a => a.toLowerCase());
6363

6464
export const parseOnBlur = (typedValue, formatString, isRangeInput) => {
65+
const parsedFormatString = parseFormatString(formatString);
66+
6567
if (isRangeInput) {
6668
const rangeValues = typedValue.split(' - ');
6769

6870
return rangeValues
69-
.map(value =>
70-
dateFnsV2.parse(
71-
value,
72-
parseFormatString(formatString, true),
73-
new Date()
74-
)
75-
)
71+
.map(value => dateFnsV2.parse(value, parsedFormatString, new Date()))
7672
.sort((a, b) => (a > b ? 1 : -1));
7773
}
7874

79-
return dateFnsV2.parse(
80-
typedValue,
81-
parseFormatString(formatString),
82-
new Date()
83-
);
75+
return dateFnsV2.parse(typedValue, parsedFormatString, new Date());
8476
};

stories/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import React from 'react';
22
import { storiesOf } from '@storybook/react';
3+
import parse from 'date-fns/parse';
34
import { Form } from 'semantic-ui-react';
45
import 'semantic-ui-css/semantic.min.css';
56
import SemanticDatepicker from '../src';
@@ -91,6 +92,8 @@ storiesOf('Examples', module)
9192
onDateChange={console.log}
9293
format="DD/MM/YYYY"
9394
locale={localePtBr}
95+
selected={parse('2018-10-01')}
96+
keepOpenOnSelect
9497
/>
9598
</Content>
9699
))

0 commit comments

Comments
 (0)