Guest User

Untitled

a guest
Jun 23rd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import moment from 'moment';
  3. // import { formatDateInputs } from '../../utils/helper_functions';
  4.  
  5. const formatDateInputs = (value) => {
  6. let input = value || '';
  7. input = input.replace(/\D/g, '');
  8.  
  9. input = input.substring(0, 8);
  10. const size = input.length;
  11.  
  12. if (size < 3) {
  13. return input;
  14. }
  15. if (size < 5) {
  16. return `${input.substring(0, 2)}/${input.substring(2, 4)}`;
  17. }
  18. if (size < 9) {
  19. return `${input.substring(0, 2)}/${input.substring(2, 4)}/${input.substring(4)}`;
  20. }
  21. };
  22.  
  23. class DatePickerCustomInput extends Component {
  24. constructor(props) {
  25. super(props);
  26.  
  27. this.state = {
  28. stateValue: '',
  29. };
  30. }
  31. componentWillMount() {
  32. this.setState({ stateValue: formatDateInputs(this.props.value) });
  33. }
  34. componentWillReceiveProps(nextProps) {
  35. if (nextProps.value) {
  36. const newValue = formatDateInputs(nextProps.value);
  37. this.setState({ stateValue: newValue });
  38. }
  39. }
  40. handleRawChange = (e) => {
  41. const date = e.target.value;
  42. const newDate = formatDateInputs(date);
  43.  
  44. this.setState({ stateValue: newDate });
  45.  
  46. if (newDate.length === 10 && moment(newDate, 'MM/DD/YYYY').isValid) {
  47. this.props.pickerOnChange(moment(newDate, 'MM/DD/YYYY').toISOString());
  48. }
  49. };
  50. render() {
  51. return (
  52. <input
  53. type="text"
  54. value={this.state.stateValue === 'Invalid date' ? '' : this.state.stateValue}
  55. onChange={this.handleRawChange}
  56. onClick={this.props.onClick}
  57. placeholder="MM/DD/YYYY"
  58. onBlur={this.props.onBlur}
  59. disabled={this.props.disabled}
  60. />
  61. );
  62. }
  63. }
  64.  
  65. export default DatePickerCustomInput;
Add Comment
Please, Sign In to add comment