diff --git a/packages/form/components/Form.astro b/packages/form/components/Form.astro index 0595d5d..f7eedb7 100644 --- a/packages/form/components/Form.astro +++ b/packages/form/components/Form.astro @@ -9,6 +9,7 @@ export interface Props { formGroups: FormGroup | FormGroup[]; readOnly?: boolean; showValidationHints?: boolean; + validateOnLoad?: boolean; submitControl?: Submit; theme?: 'light' | 'dark'; } @@ -18,6 +19,7 @@ const { formGroups = [], theme, showValidationHints = false, + validateOnLoad = false, readOnly = false, } = Astro.props; @@ -25,6 +27,22 @@ const uid = new ShortUniqueId({ length: 9 }); const formTheme = theme ?? 'light'; const formName = Array.isArray(formGroups) ? null : formGroups?.name || null; const formId = Array.isArray(formGroups) ? uid() : formGroups?.id || null; + +// if `validateOnLoad` prop is true, +// it should forced all FormControl to validate on load +if (validateOnLoad) { + if (Array.isArray(formGroups)) { + formGroups.forEach(group => + group.controls.forEach(control => + control.setValidateOnLoad(validateOnLoad) + ) + ); + } else { + formGroups.controls.forEach(control => + control.setValidateOnLoad(validateOnLoad) + ) + } +} ---
{ - if (validator) { - this.validate = validator.validate; - - const valueStr: string = this._value?.toString() || ''; - this._errors = this.validate(valueStr, validators); - } else { - // if user did not install the validator, then errors should be empty - this._errors = []; - } - }); + this.setValidateOnLoad(validateOnLoad); } get id() { @@ -149,6 +139,25 @@ export class FormControl { this._errors = this.validate(valueStr, this._validators || []); } + setValidateOnLoad(validateOnLoad: boolean) { + if (validateOnLoad) { + import('@astro-reactive/validator').then((validator) => { + if (validator) { + this.validate = validator.validate; + + const valueStr: string = this._value?.toString() || ''; + this._errors = this.validate(valueStr, this._validators); + } else { + // if user did not install the validator, then errors should be empty + this._errors = []; + } + }); + } else { + // don't do validate for server-render error messages, also set errors to empty + this._errors = []; + } + } + clearErrors() { this._errors = []; }