validate-flow-value.mdx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import { SourceCode } from '@theme';
  2. import { BasicStory } from 'components/form-materials/validate/validate-flow-value';
  3. # validateFlowValue
  4. validateFlowValue is a validation function for verifying the **requiredness and variable reference validity** of [`FlowValue`](../common/flow-value).
  5. ## Case Demonstration
  6. ### Basic Usage
  7. <BasicStory />
  8. ```tsx pure title="form-meta.tsx"
  9. import { validateFlowValue } from '@flowgram.ai/form-materials';
  10. const formMeta = {
  11. validate: {
  12. dynamic_value_input: ({ value, context }) =>
  13. validateFlowValue(value, {
  14. node: context.node,
  15. errorMessages: {
  16. required: 'Value is required',
  17. unknownVariable: 'Unknown Variable',
  18. },
  19. }),
  20. required_dynamic_value_input: ({ value, context }) =>
  21. validateFlowValue(value, {
  22. node: context.node,
  23. required: true,
  24. errorMessages: {
  25. required: 'Value is required',
  26. unknownVariable: 'Unknown Variable',
  27. },
  28. }),
  29. prompt_editor: ({ value, context }) =>
  30. validateFlowValue(value, {
  31. node: context.node,
  32. required: true,
  33. errorMessages: {
  34. required: 'Prompt is required',
  35. unknownVariable: 'Unknown Variable In Template',
  36. },
  37. }),
  38. },
  39. render: ({ form }) => (
  40. <>
  41. <FormHeader />
  42. <b>Validate variable valid</b>
  43. <Field<any> name="dynamic_value_input">
  44. {({ field, fieldState }) => (
  45. <>
  46. <DynamicValueInput
  47. value={field.value}
  48. onChange={(value) => field.onChange(value)}
  49. />
  50. <span style={{ color: 'red' }}>
  51. {fieldState.errors?.map((e) => e.message).join('\n')}
  52. </span>
  53. </>
  54. )}
  55. </Field>
  56. <br />
  57. <b>Validate required value</b>
  58. <Field<any> name="required_dynamic_value_input">
  59. {({ field, fieldState }) => (
  60. <>
  61. <DynamicValueInput
  62. value={field.value}
  63. onChange={(value) => field.onChange(value)}
  64. />
  65. <span style={{ color: 'red' }}>
  66. {fieldState.errors?.map((e) => e.message).join('\n')}
  67. </span>
  68. </>
  69. )}
  70. </Field>
  71. <br />
  72. <b>Validate required and variables valid in prompt</b>
  73. <Field<any> name="prompt_editor">
  74. {({ field, fieldState }) => (
  75. <>
  76. <PromptEditorWithVariables
  77. value={field.value}
  78. onChange={(value) => field.onChange(value)}
  79. />
  80. <span style={{ color: 'red' }}>
  81. {fieldState.errors?.map((e) => e.message).join('\n')}
  82. </span>
  83. </>
  84. )}
  85. </Field>
  86. <br />
  87. <Button onClick={() => form.validate()}>Trigger Validate</Button>
  88. </>
  89. ),
  90. };
  91. ```
  92. ## API Reference
  93. ### validateFlowValue Function
  94. ```typescript
  95. export function validateFlowValue(value: IFlowValue | undefined, ctx: Context): {
  96. level: FeedbackLevel.Error;
  97. message: string;
  98. } | undefined;
  99. ```
  100. #### Parameters
  101. | Parameter | Type | Description |
  102. |-----------|------|-------------|
  103. | `value` | `IFlowValue \| undefined` | The FlowValue to validate |
  104. | `ctx` | `Context` | Validation context |
  105. #### Context Interface
  106. ```typescript
  107. interface Context {
  108. node: FlowNodeEntity;
  109. required?: boolean; // Whether required
  110. errorMessages?: {
  111. required?: string; // Required error message
  112. unknownVariable?: string; // Unknown variable error message
  113. };
  114. }
  115. ```
  116. #### Return Value
  117. - If validation passes, returns `undefined`
  118. - If validation fails, returns an object containing error level and error message
  119. ### Supported Validation Types
  120. 1. **Required Validation**: When `required` is set to `true`, verifies if the value exists and is not empty
  121. 2. **Reference Variable Validation**: For values of type `ref`, verifies if the referenced variable exists
  122. 3. **Template Variable Validation**: For values of type `template`, verifies if all variables referenced in the template exist
  123. ## Source Code Guide
  124. <SourceCode
  125. href="https://github.com/bytedance/flowgram.ai/tree/main/packages/materials/form-materials/src/validate/validate-flow-value/index.ts"
  126. />
  127. Use the CLI command to copy the source code locally:
  128. ```bash
  129. npx @flowgram.ai/cli@latest materials validate/validate-flow-value
  130. ```
  131. ### Directory Structure
  132. ```
  133. validate-flow-value/
  134. └── index.tsx # Main function implementation, containing validateFlowValue core logic
  135. ```
  136. ### Core Implementation
  137. #### Required Validation Logic
  138. ```typescript
  139. if (required && (isNil(value) || isNil(value?.content) || value?.content === '')) {
  140. return {
  141. level: FeedbackLevel.Error,
  142. message: requiredMessage,
  143. };
  144. }
  145. ```
  146. #### Reference Variable Validation Logic
  147. ```typescript
  148. if (value?.type === 'ref') {
  149. const variable = node.scope.available.getByKeyPath(value?.content || []);
  150. if (!variable) {
  151. return {
  152. level: FeedbackLevel.Error,
  153. message: unknownVariableMessage,
  154. };
  155. }
  156. }
  157. ```
  158. #### Template Variable Validation Logic
  159. ```typescript
  160. if (value?.type === 'template') {
  161. const allRefs = FlowValueUtils.getTemplateKeyPaths(value);
  162. for (const ref of allRefs) {
  163. const variable = node.scope.available.getByKeyPath(ref);
  164. if (!variable) {
  165. return {
  166. level: FeedbackLevel.Error,
  167. message: unknownVariableMessage,
  168. };
  169. }
  170. }
  171. }
  172. ```
  173. ### Flowgram APIs Used
  174. [**@flowgram.ai/editor**](https://github.com/bytedance/flowgram.ai/tree/main/packages/client/editor)
  175. - [`FeedbackLevel`](https://flowgram.ai/auto-docs/editor/enums/FeedbackLevel): Feedback level enum
  176. ### Dependencies on Other Materials
  177. [**FlowValue**](../common/flow-value)
  178. - `IFlowValue`: FlowValue type definition
  179. - `FlowValueUtils`: FlowValue utility class
  180. - `getTemplateKeyPaths`: Method to extract all variable reference paths from templates
  181. ### Third-party Libraries
  182. [**lodash-es**](https://lodash.com/)
  183. - `isNil`: Checks if a value is null or undefined