Jelajahi Sumber

react-panel: Input validation should be optional

Johannes Schill 7 tahun lalu
induk
melakukan
c722ea4f76
2 mengubah file dengan 19 tambahan dan 12 penghapusan
  1. 13 11
      public/app/core/components/Form/Input.tsx
  2. 6 1
      public/app/core/utils/validate.ts

+ 13 - 11
public/app/core/components/Form/Input.tsx

@@ -1,6 +1,6 @@
 import React, { PureComponent } from 'react';
 import { ValidationEvents, ValidationRule } from 'app/types';
-import { validate } from 'app/core/utils/validate';
+import { validate, hasValidationEvent } from 'app/core/utils/validate';
 
 export enum InputStatus {
   Invalid = 'invalid',
@@ -21,7 +21,7 @@ export enum EventsWithValidation {
 }
 
 interface Props extends React.HTMLProps<HTMLInputElement> {
-  validationEvents: ValidationEvents;
+  validationEvents?: ValidationEvents;
   hideErrorMessage?: boolean;
 
   // Override event props and append status as argument
@@ -57,15 +57,17 @@ export class Input extends PureComponent<Props> {
 
   populateEventPropsWithStatus = (restProps, validationEvents: ValidationEvents) => {
     const inputElementProps = { ...restProps };
-    Object.keys(EventsWithValidation).forEach(eventName => {
-      inputElementProps[eventName] = async evt => {
-        if (validationEvents[eventName]) {
-          await this.validatorAsync(validationEvents[eventName]).apply(this, [evt]);
-        }
-        if (restProps[eventName]) {
-          restProps[eventName].apply(null, [evt, this.status]);
-        }
-      };
+    Object.keys(EventsWithValidation).forEach((eventName: EventsWithValidation) => {
+      if (hasValidationEvent(eventName, validationEvents) || restProps[eventName]) {
+        inputElementProps[eventName] = async evt => {
+          if (hasValidationEvent(eventName, validationEvents)) {
+            await this.validatorAsync(validationEvents[eventName]).apply(this, [evt]);
+          }
+          if (restProps[eventName]) {
+            restProps[eventName].apply(null, [evt, this.status]);
+          }
+        };
+      }
     });
     return inputElementProps;
   };

+ 6 - 1
public/app/core/utils/validate.ts

@@ -1,4 +1,5 @@
-import { ValidationRule } from 'app/types';
+import { ValidationRule, ValidationEvents } from 'app/types';
+import { EventsWithValidation } from 'app/core/components/Form/Input';
 
 export const validate = (value: string, validationRules: ValidationRule[]) => {
   const errors = validationRules.reduce((acc, currRule) => {
@@ -9,3 +10,7 @@ export const validate = (value: string, validationRules: ValidationRule[]) => {
   }, []);
   return errors.length > 0 ? errors : null;
 };
+
+export const hasValidationEvent = (event: EventsWithValidation, validationEvents: ValidationEvents) => {
+  return validationEvents && validationEvents[event];
+};