diff --git a/apps/demo/src/pages/index.astro b/apps/demo/src/pages/index.astro index fb6433f..488a307 100644 --- a/apps/demo/src/pages/index.astro +++ b/apps/demo/src/pages/index.astro @@ -11,12 +11,20 @@ const form = new FormGroup([ { name: "username", label: "Username", - validators: [Validators.required], + validators: [ + { + validator: Validators.required, + category: "info", + }, + ], }, { name: "email", label: "Email", - validators: [Validators.email, Validators.required], + validators: [ + { validator: Validators.required }, + { validator: Validators.email, category: "warn" }, + ], }, { name: "password", @@ -52,7 +60,7 @@ const form = new FormGroup([ name: "comment", label: "Feedback", type: "textarea", - value: "Nice!" + value: "Nice!", }, ]); diff --git a/packages/common/types/control.types.ts b/packages/common/types/control.types.ts index ecae957..2c6adb7 100644 --- a/packages/common/types/control.types.ts +++ b/packages/common/types/control.types.ts @@ -1,3 +1,5 @@ +import type { ValidatorRules } from "./validator.types"; + /** * `ControlType` determines the type of form control * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types @@ -34,7 +36,7 @@ export interface ControlBase { value?: string | number | string[]; label?: string; placeholder?: string; - validators?: string[]; // TODO: implement validator type + validators?: ValidatorRules; } export interface Checkbox extends ControlBase { diff --git a/packages/common/types/validator.types.ts b/packages/common/types/validator.types.ts index 915b499..0685a09 100644 --- a/packages/common/types/validator.types.ts +++ b/packages/common/types/validator.types.ts @@ -1,9 +1,16 @@ export type HookType = "onSubmit" | "onControlBlur" | "all"; +export type CategoryType = "error" | "warn" | "info"; + +export type ValidatorRules = + | string[] + | { validator: string; category?: CategoryType }[]; + export type ValidationResult = true | ValidationError; export type ValidationError = { error: string; value: string; limit?: number; + category?: string; }; diff --git a/packages/form/components/Field.astro b/packages/form/components/Field.astro index f6b479a..7a8dc2d 100644 --- a/packages/form/components/Field.astro +++ b/packages/form/components/Field.astro @@ -20,19 +20,24 @@ export interface Props { const { control, showValidationHints, showErrors = false, readOnly = false } = Astro.props; -const hasErrors: boolean | null = !!control.errors?.length; +const hasError: boolean = control.errors?.length ? control.errors[0]?.category === 'error' : false; +const hasWarn: boolean = control.errors?.length ? control.errors[0]?.category === 'warn' : false; +const hasInfo: boolean = control.errors?.length ? control.errors[0]?.category === 'info' : false; --- -
+