Input.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import React, { PureComponent } from 'react';
  2. import { ValidationEvents, ValidationRule } from 'app/types';
  3. import { validate } from 'app/core/utils/validate';
  4. export enum InputStatus {
  5. Invalid = 'invalid',
  6. Valid = 'valid',
  7. }
  8. export enum InputTypes {
  9. Text = 'text',
  10. Number = 'number',
  11. Password = 'password',
  12. Email = 'email',
  13. }
  14. export enum EventsWithValidation {
  15. onBlur = 'onBlur',
  16. onFocus = 'onFocus',
  17. onChange = 'onChange',
  18. }
  19. interface Props extends React.HTMLProps<HTMLInputElement> {
  20. validationEvents: ValidationEvents;
  21. hideErrorMessage?: boolean;
  22. // Override event props and append status as argument
  23. onBlur?: (event: React.FocusEvent<HTMLInputElement>, status?: InputStatus) => void;
  24. onFocus?: (event: React.FocusEvent<HTMLInputElement>, status?: InputStatus) => void;
  25. onChange?: (event: React.FormEvent<HTMLInputElement>, status?: InputStatus) => void;
  26. }
  27. export class Input extends PureComponent<Props> {
  28. state = {
  29. error: null,
  30. };
  31. get status() {
  32. return this.state.error ? InputStatus.Invalid : InputStatus.Valid;
  33. }
  34. get isInvalid() {
  35. return this.status === InputStatus.Invalid;
  36. }
  37. validatorAsync = (validationRules: ValidationRule[]) => {
  38. return evt => {
  39. const errors = validate(evt.currentTarget.value, validationRules);
  40. this.setState(prevState => {
  41. return {
  42. ...prevState,
  43. error: errors ? errors[0] : null,
  44. };
  45. });
  46. };
  47. };
  48. populateEventPropsWithStatus = (restProps, validationEvents: ValidationEvents) => {
  49. const inputElementProps = { ...restProps };
  50. Object.keys(EventsWithValidation).forEach(eventName => {
  51. inputElementProps[eventName] = async evt => {
  52. if (validationEvents[eventName]) {
  53. await this.validatorAsync(validationEvents[eventName]).apply(this, [evt]);
  54. }
  55. if (restProps[eventName]) {
  56. restProps[eventName].apply(null, [evt, this.status]);
  57. }
  58. };
  59. });
  60. return inputElementProps;
  61. };
  62. render() {
  63. const { validationEvents, className, hideErrorMessage, ...restProps } = this.props;
  64. const { error } = this.state;
  65. const inputClassName = 'gf-form-input' + (this.isInvalid ? ' invalid' : '');
  66. const inputElementProps = this.populateEventPropsWithStatus(restProps, validationEvents);
  67. return (
  68. <div className="our-custom-wrapper-class">
  69. <input {...inputElementProps} className={inputClassName} />
  70. {error && !hideErrorMessage && <span>{error}</span>}
  71. </div>
  72. );
  73. }
  74. }