diff --git a/README.md b/README.md index c26cb1fc..8e407bb9 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ There are five type of events that can be handled with the hooks: - [`validation:end`](#validationend) - [`validation:success`](#validationsuccess) - [`validation:failed`](#validationfailed) +- [`field:success`](#fieldsuccess) - [`field:error`](#fielderror) @@ -183,6 +184,20 @@ v.on('validation:failed', (form) => { ``` --- +#### `field:success` +This event will occur when the validation of a field was successful and no errors are thrown: +```javascript +v.on('field:success', (form, field) => { + // Do something like add a success class to display the result +}); +``` +This feature can be disabled by set the option `renderSuccess` to false while initialization in the config object: +```javascript +const v = new Validator(form, { + renderSuccess: false, +}); +``` +--- #### `field:error` When a particular field has errors, you can handle the errors with this event: ```javascript diff --git a/src/facile-validator.ts b/src/facile-validator.ts index fd4a906f..12f6bc59 100644 --- a/src/facile-validator.ts +++ b/src/facile-validator.ts @@ -11,6 +11,7 @@ type RuleKey = keyof typeof rules; const defaultOptions: ValidatorOptions = { renderErrors: true, + renderSuccess: true, onFieldChangeValidationDelay: 500, }; @@ -101,6 +102,8 @@ class Validator { if (shouldStopOnFirstFailure) { break; } + } else if(this.options.renderSuccess) { + this.events.call('field:success', this.container, field); } } catch (error) { console.error(new Error(`${ruleName}: ${(error as Error).message}`)); @@ -130,8 +133,9 @@ class Validator { const totalErrors = this.validatorError.errors; totalErrors.forEach((fieldErrors) => { - if (fieldErrors.length === 0) return; - + if (fieldErrors.length === 0) { + return; + } this.events.call('field:error', this.container, fieldErrors[0].element, fieldErrors); }); } diff --git a/src/types/index.ts b/src/types/index.ts index 83ea117d..ef686405 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -16,6 +16,7 @@ export interface ValidatorOptions { lang?: Lang; on?: Partial; renderErrors?: boolean; + renderSuccess?: boolean; xRules?: XRules; onFieldChangeValidation?: boolean; onFieldChangeValidationDelay?: number; @@ -38,6 +39,7 @@ export interface Events { 'validation:end': (container: HTMLElement, isSuccessful: boolean) => void; 'validation:success': (container: HTMLElement) => void; 'validation:failed': (container: HTMLElement) => void; + 'field:success': (container: HTMLElement, element: FormInputElement) => void; 'field:error': (container: HTMLElement, element: FormInputElement, errors: ErrorDetail[]) => void; }