Skip to content

Add field success option to events #314

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/facile-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type RuleKey = keyof typeof rules;

const defaultOptions: ValidatorOptions = {
renderErrors: true,
renderSuccess: true,
onFieldChangeValidationDelay: 500,
};

Expand Down Expand Up @@ -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}`));
Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,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;
}

Expand Down