Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Illiar/feat/kyb validation poc (DRAFT) #2578

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Jul 29, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new ValidatorPOC component to streamline form validation.
    • Added FieldList, TextInput, and SubmitButton components to enhance user input handling.
    • Implemented validation logic through new Validator component and associated hooks.
  • Routing

    • Updated routing to include a path for the new ValidatorPOC component.
  • Documentation

    • New TypeScript type definitions and context structures to improve validation mechanisms.
  • Bug Fixes

    • Restructured loading and error management for improved user experience.

Copy link

changeset-bot bot commented Jul 29, 2024

⚠️ No Changeset found

Latest commit: 030b4f9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jul 29, 2024

Walkthrough

The recent changes to the kyb-app application introduce a validation-centric architecture by restructuring the App component. This update emphasizes modularity, with the new ValidatorPOC component handling UI validation through enhanced components and hooks. The refactor aims to improve user experience and maintainability, laying a robust foundation for future enhancements in form handling and validation.

Changes

File(s) Change Summary
apps/kyb-app/src/App.tsx Restructured to comment out existing components and directly return ValidatorPOC.
apps/kyb-app/src/ValidatorPOC.tsx Introduced a new component for validating UI elements using context and child components.
apps/kyb-app/src/components/providers/Validator/*.tsx New components added to manage UI validation, including Validator, useValidate, and validation strategies.
apps/kyb-app/src/components/providers/Validator/hooks/useValidate/*.ts Introduced a validation hook for processing user input based on defined rules.
apps/kyb-app/src/poc/*.tsx New components (FieldList, SubmitButton, TextInput) to render fields and handle submissions.
apps/kyb-app/src/router.tsx Updated routing to include a new path for the ValidatorPOC component.
services/workflows-service/prisma/data-migrations Updated commit reference for Prisma data migrations, indicating a change in underlying code dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant ValidatorPOC
    participant Validator

    User->>App: Load Application
    App->>ValidatorPOC: Render Validation Interface
    ValidatorPOC->>Validator: Validate User Input
    Validator->>ValidatorPOC: Return Validation Result
    ValidatorPOC->>User: Display Validation Feedback
Loading

🐰 In a world of forms and fields we play,
With validation, we hop every day!
User inputs, checked with glee,
A happy path for you and me!
So here's to code, all shiny and bright,
Let’s validate with pure delight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Outside diff range, codebase verification and nitpick comments (1)
apps/kyb-app/src/components/providers/Validator/hooks/useValidate/useValidate.ts (1)

72-95: Remove commented-out code.

The commented-out code can be removed to improve readability and maintainability.

-    // const valiateFn = (
-    //   elements: UIElementV2[],
-    //   meta: { parent: UIElementV2 | null; deepthLevel: number } = { parent: null, deepthLevel: 0 },
-    // ) => {
-    //   for (const element of elements) {
-    //     if (element.type === 'ui') continue;
-    //
-    //     if (element.type === 'field') {
-    //       errors = [...errors, ...fieldValidationStrategy(element, meta?.parent || undefined)];
-    //     }
-    //
-    //     if (element.type === 'field-list') {
-    //       errors = [...errors, ...arrayValidationStrategy(element, meta.deepthLevel)];
-    //     }
-    //
-    //     if (element.children) {
-    //       valiateFn(element.children, {
-    //         ...meta,
-    //         deepthLevel: meta.deepthLevel + 1,
-    //         parent: element,
-    //       });
-    //     }
-    //   }
-    // };
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f8d4585 and 28fc959.

Files selected for processing (26)
  • apps/kyb-app/src/App.tsx (2 hunks)
  • apps/kyb-app/src/ValidatorPOC.tsx (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/Validator.tsx (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/index.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/useValidate.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidatedInput/index.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidatedInput/useValidatedInput.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidator/index.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidator/useValidator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/index.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/types.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/validator.context.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validator-manager.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/value-validator.abstract.ts (1 hunks)
  • apps/kyb-app/src/poc-definition.ts (1 hunks)
  • apps/kyb-app/src/poc/FieldList/FieldList.tsx (1 hunks)
  • apps/kyb-app/src/poc/FieldList/index.ts (1 hunks)
  • apps/kyb-app/src/poc/SubmitButton/SubmitButton.tsx (1 hunks)
  • apps/kyb-app/src/poc/SubmitButton/index.ts (1 hunks)
  • apps/kyb-app/src/poc/TextInput/TextInput.tsx (1 hunks)
  • apps/kyb-app/src/poc/TextInput/index.ts (1 hunks)
  • apps/kyb-app/src/router.tsx (2 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
Files skipped from review due to trivial changes (8)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/index.ts
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidatedInput/index.ts
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidator/index.ts
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidator/useValidator.ts
  • apps/kyb-app/src/components/providers/Validator/index.ts
  • apps/kyb-app/src/poc/FieldList/index.ts
  • apps/kyb-app/src/poc/SubmitButton/index.ts
  • apps/kyb-app/src/poc/TextInput/index.ts
Additional context used
Biome
apps/kyb-app/src/components/providers/Validator/types.ts

[error] 11-11: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts

[error] 20-20: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)


[error] 20-20: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)

Additional comments not posted (61)
services/workflows-service/prisma/data-migrations (1)

1-1: Verify the impact of the updated subproject commit.

The subproject commit reference has been updated. Ensure that the new commit b5b8cded73bdeafe792b5e5cb51780ae8a2c58a7 does not introduce breaking changes or regressions.

apps/kyb-app/src/components/providers/Validator/value-validators/value-validator.abstract.ts (1)

1-5: LGTM!

The ValueValidator abstract class is well-defined, ensuring that subclasses implement the validate method.

apps/kyb-app/src/components/providers/Validator/hooks/useValidatedInput/useValidatedInput.ts (1)

1-8: LGTM!

The useValidatedInput hook is well-implemented, providing a clean way to retrieve validation errors for a given UI element.

apps/kyb-app/src/components/providers/Validator/validator.context.ts (2)

1-5: LGTM!

The imports and type definitions are correctly defined.


6-12: LGTM!

The interface IValidatorContext and context creation are correctly defined.

apps/kyb-app/src/poc/SubmitButton/SubmitButton.tsx (3)

1-4: LGTM!

The imports and component definition are correctly defined.


6-12: LGTM!

The handleSubmit function is correctly defined.


14-20: LGTM!

The button rendering is correctly defined.

apps/kyb-app/src/components/providers/Validator/types.ts (2)

1-10: LGTM!

The type definitions are correctly defined.


13-25: LGTM!

The UIElementV2 interface is correctly defined.

apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts (2)

1-7: LGTM!

The imports and interface definition look good.


9-14: LGTM!

The validate method correctly handles validation for required values.

apps/kyb-app/src/components/providers/Validator/value-validator-manager.ts (2)

1-8: LGTM!

The imports and validators map look good.


10-13: LGTM!

The type definition and constructor look good.

apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.ts (2)

1-6: LGTM!

The imports and interface definition look good.


8-13: LGTM!

The validate method correctly handles validation for minimum length.

apps/kyb-app/src/poc/FieldList/FieldList.tsx (3)

1-4: Imports look good.

The imported modules and hooks are necessary for the functionality of the FieldList component.


6-11: Interface definition looks good.

The IFieldListProps interface is correctly defined and includes all necessary properties for the FieldList component.


13-33: Component implementation looks good.

The FieldList component is correctly implemented, using useMemo and useValidatedInput hooks appropriately. The rendering logic is sound and handles errors correctly.

apps/kyb-app/src/router.tsx (2)

6-7: Imports look good.

The import statements are correctly adjusted to include the ValidatorPOC component.


44-47: Routing configuration looks good.

The new route for the ValidatorPOC component is correctly added and the routing configuration is sound.

apps/kyb-app/src/poc/TextInput/TextInput.tsx (3)

1-6: Imports look good.

The imported modules, hooks, and components are necessary for the functionality of the TextInput component.


8-12: Interface definition looks good.

The ITextInputProps interface is correctly defined and includes all necessary properties for the TextInput component.


14-31: Component implementation looks good.

The TextInput component is correctly implemented, using useMemo, useValidatedInput, and useCallback hooks appropriately. The rendering logic is sound and handles errors correctly.

apps/kyb-app/src/App.tsx (3)

5-5: LGTM!

The import statement for ValidatorPOC is correct.


19-31: Verify the architectural change.

The original implementation, including several components, has been commented out. Ensure that this change is intentional and doesn't break the application.


32-32: LGTM! But verify the implementation of ValidatorPOC.

The App component now returns ValidatorPOC. Ensure that ValidatorPOC is correctly implemented and integrated.

Verification successful

LGTM! The implementation of ValidatorPOC is correct and properly integrated.

  • ValidatorPOC is defined in apps/kyb-app/src/ValidatorPOC.tsx.
  • It imports and uses several components and definitions.
  • The form submission and nested input fields are handled correctly.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of `ValidatorPOC`.

# Test: Search for the implementation of `ValidatorPOC`. Expect: Correct implementation and integration.
rg --type tsx 'ValidatorPOC'

Length of output: 56


Script:

#!/bin/bash
# Description: Verify the implementation of `ValidatorPOC`.

# Add `tsx` as a recognized file type and search for `ValidatorPOC`.
rg --type-add 'tsx:*.tsx' 'ValidatorPOC'

Length of output: 366


Script:

#!/bin/bash
# Description: Display the contents of `ValidatorPOC.tsx` to verify its implementation.

cat apps/kyb-app/src/ValidatorPOC.tsx

Length of output: 3866

apps/kyb-app/src/components/providers/Validator/Validator.tsx (2)

1-5: LGTM!

The import statements are correct and necessary for the component's functionality.


9-13: LGTM!

The IValidatorProps interface is correctly defined and necessary for type safety.

apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (13)

1-10: LGTM!

The import statements are correct and necessary for the class's functionality.


12-13: LGTM!

The constructor is correctly implemented.


15-17: LGTM!

The getId method is correctly implemented.


19-21: LGTM!

The getOriginId method is correctly implemented.


23-25: LGTM!

The formatId method is correctly implemented.


27-29: LGTM!

The getValueDestination method is correctly implemented.


31-33: LGTM!

The formatValueDestination method is correctly implemented.


35-41: LGTM!

The formatValueAndApplyStackIndexes method is correctly implemented.


43-47: LGTM!

The getValue method is correctly implemented.


49-55: LGTM!

The getValidatorsParams method is correctly implemented.


58-67: LGTM!

The getValidatorParams method is correctly implemented.


69-91: LGTM!

The getMinLengthParams method is correctly implemented.


93-115: LGTM!

The getRequiredParams method is correctly implemented.

apps/kyb-app/src/components/providers/Validator/hooks/useValidate/useValidate.ts (8)

1-4: Imports look good.

The import statements are appropriate for the functionality provided in the file.


6-9: Interface definition looks good.

The IUseValidateParams interface is well-defined and appropriately typed.


11-17: Interface definition looks good.

The IValidationError interface is well-defined and appropriately typed.


19-23: Hook definition looks good.

The useValidate hook is well-structured and uses useCallback appropriately.


24-46: Field validation strategy looks good.

The fieldValidationStrategy function is well-defined and handles validation errors appropriately.


48-70: Validation function looks good.

The validateFn function is well-structured and appropriately handles different element types and recursion.


97-99: Validation function invocation looks good.

The invocation of validateFn with the provided elements and context is appropriate.


102-103: Return statement looks good.

The return statement of the useValidate hook is appropriate and ensures the validation function is accessible.

apps/kyb-app/src/ValidatorPOC.tsx (5)

1-16: Imports and context definition look good.

The import statements are appropriate for the functionality provided in the file. The context object is well-defined and structured.


18-26: Component definition looks good.

The ValidatorPOC component is well-structured and follows React best practices. The form submission handler is appropriately defined.


27-99: Nested components look good.

The nested TextInput and FieldList components are well-structured and appropriately utilize the context and element props. The usage of stack ensures proper handling of nested elements.


100-101: SubmitButton component looks good.

The SubmitButton component is appropriately placed within the form.


102-103: Return statement looks good.

The return statement of the ValidatorPOC component is appropriate and ensures the form is wrapped in the Validator component.

apps/kyb-app/src/poc-definition.ts (6)

1-2: Imports look good.

The import statements are appropriate for the functionality provided in the file.


4-128: pocDefinition array looks good.

The pocDefinition array is well-defined and appropriately structured. The validation rules are clearly specified.


131-138: Context object looks good.

The context object is well-defined and structured.


140-146: Function definition looks good.

The formatDestination function is well-defined and appropriately handles the formatting.


148-168: Iteration function looks good.

The iterate function is well-structured and appropriately handles different element types. The recursion ensures nested elements are processed.


170-170: Iteration function invocation looks good.

The invocation of iterate with the pocDefinition and context is appropriate.

Comment on lines +15 to +22
validate<TValidatorParams extends IBaseValueValidatorParams>(
value: unknown,
key: TValidator,
params: TValidatorParams,
) {
const validator = new this.validators[key](params as any);
return validator.validate(value as any);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid using any type.

The usage of any type should be avoided. Consider using a more specific type or a generic type.

-    const validator = new this.validators[key](params as any);
-    return validator.validate(value as any);
+    const validator = new this.validators[key](params);
+    return validator.validate(value);

Committable suggestion was skipped due to low confidence.

Comment on lines 15 to 28
static isMinLengthParams = (params: unknown): params is TMinLengthValidationParams => {
if (typeof params === 'boolean') return true;

//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}

return false;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the typeof comparison and avoid @ts-ignore.

The typeof comparison on line 21 is invalid. It should compare against a string literal. The @ts-ignore comment should be avoided if possible.

-    //@ts-ignore
-    if (Array.isArray(params) && typeof params?.[0] === number && typeof params?.[1] === string) {
+    if (Array.isArray(params) && typeof params?.[0] === 'number' && typeof params?.[1] === 'string') {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static isMinLengthParams = (params: unknown): params is TMinLengthValidationParams => {
if (typeof params === 'boolean') return true;
//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}
return false;
};
static isMinLengthParams = (params: unknown): params is TMinLengthValidationParams => {
if (typeof params === 'boolean') return true;
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}
return false;
};

Comment on lines +15 to +40
export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});

const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;

return acc;
}, {} as TValidationErrors);

setValiationErrors(validationErrors);

console.log({ errors, validationErrors });

return Boolean(errors.length);
}, [validate]);

const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);

return <Provider value={ctx}>{children}</Provider>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the typo in the state setter function name.

The state setter function setValiationErrors should be setValidationErrors.

-  const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});
+  const [validationErrors, setValidationErrors] = useState<TValidationErrors>({});
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});
const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;
return acc;
}, {} as TValidationErrors);
setValiationErrors(validationErrors);
console.log({ errors, validationErrors });
return Boolean(errors.length);
}, [validate]);
const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);
return <Provider value={ctx}>{children}</Provider>;
export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValidationErrors] = useState<TValidationErrors>({});
const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;
return acc;
}, {} as TValidationErrors);
setValidationErrors(validationErrors);
console.log({ errors, validationErrors });
return Boolean(errors.length);
}, [validate]);
const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);
return <Provider value={ctx}>{children}</Provider>;

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 28fc959 and 43dd5d4.

Files selected for processing (2)
  • apps/kyb-app/src/ValidatorPOC.tsx (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/useValidate.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • apps/kyb-app/src/ValidatorPOC.tsx
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/useValidate.ts

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (36)
apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.unit.test.ts (8)

5-9: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is undefined. Consider adding more edge cases like NaN or an empty array for thoroughness.

+    test('when value is NaN', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate(NaN)).toThrowError('error');
+    });

11-15: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is an empty string. Consider adding more edge cases like an empty array for thoroughness.

+    test('when value is an empty array', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate([])).toThrowError('error');
+    });

17-21: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is null. Consider adding more edge cases like an empty object for thoroughness.

+    test('when value is an empty object', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate({})).toThrowError('error');
+    });

25-29: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is a non-empty string. Consider adding more edge cases like a non-empty array for thoroughness.

+    test('when value is a non-empty array', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate([1])).not.toThrow();
+    });

31-35: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is not null. Consider adding more edge cases like a non-empty object for thoroughness.

+    test('when value is a non-empty object', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate({ key: 'value' })).not.toThrow();
+    });

37-41: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is not undefined. Consider adding more edge cases like a boolean true for thoroughness.

+    test('when value is true', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate(true)).not.toThrow();
+    });

45-49: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when the default error message is used. Consider adding more edge cases like different data types for thoroughness.

+    test('should return default error message when value is 0', () => {
+      const validator = new RequiredValueValidator({ required: true });
+      expect(() => validator.validate(0)).toThrowError('Value is required.');
+    });

51-55: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when a custom error message is provided. Consider adding more edge cases like different data types for thoroughness.

+    test('should return custom error message when value is 0', () => {
+      const validator = new RequiredValueValidator({ message: 'error', required: true });
+      expect(() => validator.validate(0)).toThrowError('error');
+    });
apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.unit.test.ts (9)

5-9: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is undefined. Consider adding more edge cases like NaN or an empty array for thoroughness.

+    test('when value is NaN', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate(NaN)).toThrowError('error');
+    });

11-15: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is below the minimum length. Consider adding more edge cases like an empty array for thoroughness.

+    test('when value is an empty array', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate([])).toThrowError('error');
+    });

17-21: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is null. Consider adding more edge cases like an empty object for thoroughness.

+    test('when value is an empty object', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate({})).toThrowError('error');
+    });

25-29: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is above the minimum length. Consider adding more edge cases like a non-empty array for thoroughness.

+    test('when value is a non-empty array', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate([1, 2, 3, 4, 5, 6])).not.toThrow();
+    });

31-35: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is equal to the minimum length. Consider adding more edge cases like a non-empty object for thoroughness.

+    test('when value is a non-empty object', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate({ key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4', key5: 'value5' })).not.toThrow();
+    });

39-43: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when the default error message is used. Consider adding more edge cases like different data types for thoroughness.

+    test('should return default error message when value is 0', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5 });
+      expect(() => validator.validate(0)).toThrowError('Minimum length is 5.');
+    });

45-49: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when a custom error message is provided. Consider adding more edge cases like different data types for thoroughness.

+    test('should return custom error message when value is 0', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate(0)).toThrowError('error');
+    });

51-55: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when the {minLength} tag is interpolated. Consider adding more edge cases like different data types for thoroughness.

+    test('should interpolate {minLength} with the provided value when value is 0', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error {minLength}' });
+      expect(() => validator.validate(0)).toThrowError('error 5');
+    });

57-61: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when the error message does not contain the interpolation tag. Consider adding more edge cases like different data types for thoroughness.

+    test('error message should stay same if interpolation tag is not present when value is 0', () => {
+      const validator = new MinLengthValueValidator({ minLength: 5, message: 'error' });
+      expect(() => validator.validate(0)).toThrowError('error');
+    });
apps/kyb-app/src/components/providers/Validator/value-validators/max-length.value.validator.unit.test.ts (6)

5-9: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is undefined. Consider adding more edge cases like NaN or an empty array for thoroughness.

+    test('when value is NaN', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5, message: 'error' });
+      expect(() => validator.validate(NaN)).toThrowError('error');
+    });

11-15: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is above the maximum length. Consider adding more edge cases like an empty array for thoroughness.

+    test('when value is an empty array', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5, message: 'error' });
+      expect(() => validator.validate([])).toThrowError('error');
+    });

17-21: Ensure comprehensive testing of validation failure scenarios.

The test correctly handles the case when the value is null. Consider adding more edge cases like an empty object for thoroughness.

+    test('when value is an empty object', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5, message: 'error' });
+      expect(() => validator.validate({})).toThrowError('error');
+    });

25-29: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is below the maximum length. Consider adding more edge cases like a non-empty array for thoroughness.

+    test('when value is a non-empty array', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5, message: 'error' });
+      expect(() => validator.validate([1, 2, 3, 4, 5])).not.toThrow();
+    });

31-35: Ensure comprehensive testing of validation success scenarios.

The test correctly handles the case when the value is equal to the maximum length. Consider adding more edge cases like a non-empty object for thoroughness.

+    test('when value is a non-empty object', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5, message: 'error' });
+      expect(() => validator.validate({ key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4', key5: 'value5' })).not.toThrow();
+    });

39-43: Ensure comprehensive testing of error message scenarios.

The test correctly handles the case when the default error message is used. Consider adding more edge cases like different data types for thoroughness.

+    test('should return default error message when value is 0', () => {
+      const validator = new MaxLengthValueValidator({ maxLength: 5 });
+      expect(() => validator.validate(0)).toThrowError('Maximum length is 5.');
+    });
apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (13)

16-17: Consider adding type annotations for constructor parameters.

Adding type annotations for element, context, and stack parameters can improve code readability and maintainability.

-  constructor(readonly element: UIElementV2, readonly context: unknown, readonly stack: number[]) {}
+  constructor(readonly element: UIElementV2, readonly context: any, readonly stack: number[]) {}

19-21: Consider adding return type annotations for public methods.

Adding return type annotations for public methods can improve code readability and maintainability.

-  getId() {
+  getId(): string {

23-25: Consider adding return type annotations for public methods.

Adding return type annotations for public methods can improve code readability and maintainability.

-  getOriginId() {
+  getOriginId(): string {

31-33: Consider adding return type annotations for public methods.

Adding return type annotations for public methods can improve code readability and maintainability.

-  getValueDestination() {
+  getValueDestination(): string {

47-51: Consider adding return type annotations for public methods.

Adding return type annotations for public methods can improve code readability and maintainability.

-  getValue() {
+  getValue(): any {

53-59: Consider adding return type annotations for public methods.

Adding return type annotations for public methods can improve code readability and maintainability.

-  getValidatorsParams() {
+  getValidatorsParams(): { validator: string, params: any }[] {

27-29: Consider adding return type annotations for private methods.

Adding return type annotations for private methods can improve code readability and maintainability.

-  private formatId(id: string) {
+  private formatId(id: string): string {

35-37: Consider adding return type annotations for private methods.

Adding return type annotations for private methods can improve code readability and maintainability.

-  private formatValueDestination(valueDestination: string) {
+  private formatValueDestination(valueDestination: string): string {

39-45: Consider adding return type annotations for private methods.

Adding return type annotations for private methods can improve code readability and maintainability.

-  private formatValueAndApplyStackIndexes(value: string) {
+  private formatValueAndApplyStackIndexes(value: string): string {

62-72: Improve error handling in getValidatorParams method.

The method throws a generic error message. Consider providing more context in the error message to aid debugging.

-        throw new Error('Invalid key');
+        throw new Error(`Invalid validator key: ${key}`);

75-97: Improve error handling in getMinLengthParams method.

The method throws a generic error message. Consider providing more context in the error message to aid debugging.

-    throw new Error('Invalid params');
+    throw new Error(`Invalid minLength params: ${_params}`);

99-121: Improve error handling in getMaxLengthParams method.

The method throws a generic error message. Consider providing more context in the error message to aid debugging.

-    throw new Error('Invalid params');
+    throw new Error(`Invalid maxLength params: ${_params}`);

123-145: Improve error handling in getRequiredParams method.

The method throws a generic error message. Consider providing more context in the error message to aid debugging.

-    throw new Error('Invalid params');
+    throw new Error(`Invalid required params: ${_params}`);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 43dd5d4 and cb03f45.

Files selected for processing (9)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/types.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validator-manager.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/max-length.value.validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/max-length.value.validator.unit.test.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.unit.test.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.unit.test.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • apps/kyb-app/src/components/providers/Validator/value-validator-manager.ts
  • apps/kyb-app/src/components/providers/Validator/value-validators/min-length.value.validator.ts
Additional context used
Biome
apps/kyb-app/src/components/providers/Validator/types.ts

[error] 16-16: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts

[error] 28-28: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)


[error] 28-28: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)

Additional comments not posted (17)
apps/kyb-app/src/components/providers/Validator/types.ts (8)

1-1: LGTM!

The type alias TValidatorErrorMessage is correctly defined.


3-3: LGTM!

The type alias TRequiredValidationParams is correctly defined.


5-5: LGTM!

The type alias TMinLengthValidationParams is correctly defined.


7-7: LGTM!

The type alias TMaxLengthValidationParams is correctly defined.


9-12: LGTM!

The type alias TValidationParams is correctly defined.


14-14: LGTM!

The type alias TValidators is correctly defined.


18-26: LGTM!

The interface UIElementV2 is well-defined and covers all necessary properties for a UI element.


28-30: LGTM!

The interface IBaseValueValidatorParams is well-defined and provides flexibility for value validators.

apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts (4)

1-5: LGTM!

The imports are correct and necessary for the implementation.


7-9: LGTM!

The interface IRequiredValueValidatorParams is well-defined and correctly extends the base interface.


12-16: LGTM!

The validate method is correctly implemented and performs the necessary validation.


18-22: LGTM!

The getErrorMessage method is correctly implemented and provides flexibility for error messages.

apps/kyb-app/src/components/providers/Validator/value-validators/max-length.value.validator.ts (4)

1-5: LGTM!

The imports are correct and necessary for the implementation.


7-9: LGTM!

The interface IMaxLengthValueValidatorParams is well-defined and correctly extends the base interface.


12-16: LGTM!

The validate method is correctly implemented and performs the necessary validation.


18-26: LGTM!

The getErrorMessage method is correctly implemented and provides flexibility for error messages.

apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (1)

1-14: Ensure all imported modules are necessary.

Verify that all the imported modules are used within the file. Unused imports can be removed to improve code clarity and reduce potential maintenance overhead.


export type TValidators = 'required' | 'minLength' | 'maxLength';

export interface IBaseFieldParams {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace the empty interface with a type alias.

An empty interface is equivalent to {}.

- export interface IBaseFieldParams {}
+ export type IBaseFieldParams = {};
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface IBaseFieldParams {}
export type IBaseFieldParams = {};
Tools
Biome

[error] 16-16: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

Comment on lines 24 to 33
static isRequiredParams = (params: unknown): params is TRequiredValidationParams => {
if (typeof params === 'boolean') return true;

//@ts-ignore
if (Array.isArray(params) && typeof params?.[0] === number && typeof params?.[1] === string) {
return true;
}

return false;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the typeof comparison and avoid @ts-ignore.

The typeof comparison on line 28 is invalid. It should compare against a string literal. The @ts-ignore comment should be avoided if possible.

-    //@ts-ignore
-    if (Array.isArray(params) && typeof params?.[0] === number && typeof params?.[1] === string) {
+    if (Array.isArray(params) && typeof params?.[0] === 'number' && typeof params?.[1] === 'string') {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static isRequiredParams = (params: unknown): params is TRequiredValidationParams => {
if (typeof params === 'boolean') return true;
//@ts-ignore
if (Array.isArray(params) && typeof params?.[0] === number && typeof params?.[1] === string) {
return true;
}
return false;
};
static isRequiredParams = (params: unknown): params is TRequiredValidationParams => {
if (typeof params === 'boolean') return true;
if (Array.isArray(params) && typeof params?.[0] === 'number' && typeof params?.[1] === 'string') {
return true;
}
return false;
};
Tools
Biome

[error] 28-28: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)


[error] 28-28: Invalid typeof comparison value: this expression is not a string literal

not a string literal
Unsafe fix: Compare the result of typeof with a valid type name

(lint/suspicious/useValidTypeof)

Comment on lines +28 to +41
static isMaxLengthParams = (params: unknown): params is TMaxLengthValidationParams => {
if (typeof params === 'number') return true;

//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}

return false;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the typeof comparison and avoid @ts-ignore.

The typeof comparison on line 34 is invalid. It should compare against a string literal. The @ts-ignore comment should be avoided if possible.

-    //@ts-ignore
-    if (Array.isArray(params) && typeof params?.[0] === number && typeof params?.[1] === string) {
+    if (Array.isArray(params) && typeof params?.[0] === 'number' && typeof params?.[1] === 'string') {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static isMaxLengthParams = (params: unknown): params is TMaxLengthValidationParams => {
if (typeof params === 'number') return true;
//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}
return false;
};
static isMaxLengthParams = (params: unknown): params is TMaxLengthValidationParams => {
if (typeof params === 'number') return true;
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}
return false;
};

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cb03f45 and 030b4f9.

Files selected for processing (6)
  • apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/types.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/pattern.value.validator.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/pattern.value.validator.unit.test.ts (1 hunks)
  • apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts (1 hunks)
  • apps/kyb-app/src/poc-definition.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • apps/kyb-app/src/components/providers/Validator/types.ts
  • apps/kyb-app/src/components/providers/Validator/value-validators/required.value-validator.ts
  • apps/kyb-app/src/poc-definition.ts
Additional comments not posted (24)
apps/kyb-app/src/components/providers/Validator/value-validators/pattern.value.validator.ts (5)

7-9: Interface definition looks good.

The IPatternValidatorParams interface correctly extends IBaseValueValidatorParams and adds a pattern property.


18-23: Method definition looks good.

The getErrorMessage method correctly returns a custom error message if provided, otherwise a default message.


1-5: Imports look good.

The necessary types and base classes are correctly imported.


11-11: Class definition looks good.

The PatternValueValidator class is correctly defined and extends ValueValidator.


1-39: File structure looks good.

The file structure is clear and maintains readability.

apps/kyb-app/src/components/providers/Validator/value-validators/pattern.value.validator.unit.test.ts (6)

5-9: Test case looks good.

The test case correctly sets up a validator and expects an error when the value does not match the pattern.


11-15: Test case looks good.

The test case correctly sets up a validator and expects an error when the value is null.


19-23: Test case looks good.

The test case correctly sets up a validator and expects no error when the value matches the pattern.


27-31: Test case looks good.

The test case correctly sets up a validator and expects the default error message when no custom message is provided.


33-37: Test case looks good.

The test case correctly sets up a validator and expects the custom error message when provided.


39-51: Test case looks good.

The test case correctly sets up a validator and expects the error message to interpolate the pattern.

apps/kyb-app/src/components/providers/Validator/hooks/useValidate/ui-element.ts (13)

21-21: Constructor looks good.

The constructor correctly initializes the UIElement with element, context, and stack.


23-25: Method definition looks good.

The getId method correctly returns the formatted ID of the element.


27-29: Method definition looks good.

The getOriginId method correctly returns the original ID of the element.


31-33: Method definition looks good.

The formatId method correctly formats the ID by appending the stack values.


35-37: Method definition looks good.

The getValueDestination method correctly returns the formatted value destination.


39-41: Method definition looks good.

The formatValueDestination method correctly formats the value destination by applying stack indexes.


43-49: Method definition looks good.

The formatValueAndApplyStackIndexes method correctly formats the value by applying stack indexes.


51-55: Method definition looks good.

The getValue method correctly returns the value from the context using the value destination.


57-63: Method definition looks good.

The getValidatorsParams method correctly returns an array of validator parameters.


66-78: Method definition looks good.

The getValidatorParams method correctly returns the appropriate validator parameters based on the key.


81-103: Method definition looks good.

The getMinLengthParams method correctly returns the minimum length validator parameters.


105-127: Method definition looks good.

The getMaxLengthParams method correctly returns the maximum length validator parameters.


129-151: Method definition looks good.

The getRequiredParams method correctly returns the required validator parameters.

Comment on lines +12 to +16
validate(value: unknown) {
if (!new RegExp(this.params.pattern).test(value as string)) {
throw new Error(this.getErrorMessage());
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle non-string values gracefully.

The validate method should handle non-string values more gracefully to avoid runtime errors.

-    if (!new RegExp(this.params.pattern).test(value as string)) {
+    if (typeof value !== 'string' || !new RegExp(this.params.pattern).test(value)) {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
validate(value: unknown) {
if (!new RegExp(this.params.pattern).test(value as string)) {
throw new Error(this.getErrorMessage());
}
}
validate(value: unknown) {
if (typeof value !== 'string' || !new RegExp(this.params.pattern).test(value)) {
throw new Error(this.getErrorMessage());
}
}

Comment on lines +25 to +38
static isPatternParams = (params: unknown): params is TPatternValidationParams => {
if (typeof params === 'boolean') return true;

//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}

return false;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid using @ts-ignore.

The isPatternParams method should avoid using @ts-ignore and handle the type check more explicitly.

-    //@ts-ignore
     if (
       Array.isArray(params) &&
       typeof params?.[0] === 'number' &&
       typeof params?.[1] === 'string'
     ) {
       return true;
     }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static isPatternParams = (params: unknown): params is TPatternValidationParams => {
if (typeof params === 'boolean') return true;
//@ts-ignore
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}
return false;
};
if (
Array.isArray(params) &&
typeof params?.[0] === 'number' &&
typeof params?.[1] === 'string'
) {
return true;
}

Comment on lines +153 to +175
private getPatternParams() {
const _params = this.element.validation.pattern;

if (PatternValueValidator.isPatternParams(_params)) {
if (Array.isArray(_params)) {
return {
required: _params[0],
message: _params[1],
};
}

const pattern = _params;

const params: IPatternValidatorParams = {
pattern,
message: `Value must match {pattern}.`,
};

return params;
}

throw new Error('Invalid params');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix typo in returned object.

The getPatternParams method has a typo in the returned object where required should be pattern.

-        required: _params[0],
+        pattern: _params[0],
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private getPatternParams() {
const _params = this.element.validation.pattern;
if (PatternValueValidator.isPatternParams(_params)) {
if (Array.isArray(_params)) {
return {
required: _params[0],
message: _params[1],
};
}
const pattern = _params;
const params: IPatternValidatorParams = {
pattern,
message: `Value must match {pattern}.`,
};
return params;
}
throw new Error('Invalid params');
}
private getPatternParams() {
const _params = this.element.validation.pattern;
if (PatternValueValidator.isPatternParams(_params)) {
if (Array.isArray(_params)) {
return {
pattern: _params[0],
message: _params[1],
};
}
const pattern = _params;
const params: IPatternValidatorParams = {
pattern,
message: `Value must match {pattern}.`,
};
return params;
}
throw new Error('Invalid params');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant