# NgxFieldValidationErrors 🛠️

[Live Demo](https://stackblitz.com/edit/stackblitz-starters-qqj3og4k?file=src%2Fapp%2Fapp.ts)

**NgxFieldValidationErrors** is an Angular library that streamlines form validation by automatically managing and displaying error messages for form controls. It works with both template-driven and reactive forms, offering a minimal setup and flexible configuration.

---

## Angular Version Support
![Angular 17+](https://img.shields.io/badge/Angular-17%2B-1976d2?style=for-the-badge&logo=angular)
![Angular 18+](https://img.shields.io/badge/Angular-18%2B-1976d2?style=for-the-badge&logo=angular)
![Angular 19+](https://img.shields.io/badge/Angular-19%2B-1976d2?style=for-the-badge&logo=angular)

---

## 📦 Installation

```bash
npm install ngx-field-validation-errors
# or
yarn add ngx-field-validation-errors
```

Include the stylesheet in your `angular.json` or import directly:

```json
"styles": [
  "node_modules/ngx-field-validation-errors/src/styles/ngx-error.css",
  "src/styles.css"
]
```

---

## ⚙️ Global Configuration (provideNgxFieldValidation)

The library exposes a provider function you add to your application-level providers array. This function accepts an optional `IErrorConfig` object, which controls default behaviour and templates.

```ts
import { provideNgxFieldValidation } from 'ngx-field-validation-errors';

export const appConfig: ApplicationConfig = {
  providers: [
    provideNgxFieldValidation({
      defaultErrorTemplate: true,
      showFieldError: 'single',
      defaultErrorTemplateType: 'plain-text-error',
      errorFieldBorderStyle: 'dashed',
      // you can override or extend templates by supplying keys here
      errorTemplate: {
         // Overrides the default 'required' validation message.
         // Use '{name}' as a placeholder to dynamically inject the field name.
         // Similarly, you can override any built-in validation message
        // (e.g., 'minlength', 'maxlength', 'email', etc.) by providing the corresponding key.
        required: 'Please enter a {name}',

        // Defines a custom validation message for a user-defined validator key.
        // The key ('invalidUsername') should match the validation error returned by the control.
       invalidUsername: 'Username already exists.'
      }
    })
  ]
};
```

> **Note:** if you omit the `errorTemplate` property entirely, the built‑in default
> messages (provided by the library) are used.  Supplying your own object simply
> merges onto the defaults, so you only need to define custom keys or override
> specific messages.
### `IErrorConfig` fields

| Property                  | Type                                          | Description |
|---------------------------|-----------------------------------------------|-------------|
| `showFieldError`          | `'multiple' \| 'single'`                     | Whether to display one message per field or all messages. |
| `errorFieldBorderStyle?`   | `'solid' \| 'dashed' \| 'none'`             | (optional) Border style applied to invalid inputs. |
| `errorTemplate?`           | `Record<string,string>` \| `IErrorTemplate`   | (optional) Custom templates keyed by error name. |
| `defaultErrorTemplate?`    | `boolean`                                     | (optional) Render the default error template for fields. |
| `defaultErrorTemplateType?`| `'icon-text-error' \| 'plain-text-error'`         | (optional) Style of the default template. |

> The provider merges the supplied config with library defaults and registers related services (template registry, event plugin, validators).

---

## 🔧 Field Directive: `ngx-error`

Attach this directive to an input or control container to manage error state and optionally render a default message.

### Inputs

| Input        | Type         | Value | Description |
|--------------|--------------|---------------|-------------|
| `ngxError`   | `IFieldConfig` | `{ name: 'field' }` | Configuration object controlling how errors are handled for a specific control. The `name` property is required—users must supply it. See below for fields. |

#### `IFieldConfig` properties

| Property                | Type       | Default             | Description |
|-------------------------|------------|---------------------|-------------|
| `name`                  | `string`   | **required**        | {name} as a placeholder to dynamically inject the field name into the error message. |
| `defaultErrorTemplate`  | `boolean`  | `true`              | If `true`, the default template (text or icon) will be rendered for this field. Can override global setting. |
| `skipOnValidate`        | `boolean`  | `false`             | When `true`, this field ignores `(click.validate)` events, keeping errors hidden until the control is touched/dirty. |

### `IFieldConfig` shape
```ts
interface IFieldConfig {
  name: string;               // field name for message
  defaultErrorTemplate?: boolean; // render default template
  skipOnValidate?: boolean;   // ignore validateOnEvent triggers
}
```

### Example
Angular property binding:
```html
<input [ngxError]="{ name: 'Password', defaultErrorTemplate: false }" ... />
```

### Validate event (show all field errors)

If you want errors to appear for every field only when the user attempts to submit, the library supports a simple `(click.validate)` listener on a button (or any interactive element):

```html
<button (click.validate)="onSubmit()">Submit</button>
```

Clicking such an element tells all active `ngx-error` directives to update their messages and display any validation problems. Fields configured with `skipOnValidate` will ignore these notifications. This pattern keeps the form clean until the user hits the submit control.

> No additional setup is required beyond adding the directive to your inputs.

---

## 🔁 Component: `<ngx-validation-error>`

Renders validation messages for a control. It locates error text from the `Validation` service and supports custom templates.

### Inputs & slots

| Input / Template        | Type                      | Description |
|-------------------------|---------------------------|-------------|
| `for`                   |  template ref | Identifier passed to the directive or component to resolve errors. |
| `#customProjectTemplate` | `<ng-template>`            | Optional projected template. Receives context `{ error: string }`. |

### Usage examples

Basic usage (uses global/default messages):
```html
<input formControlName="email" #email="ngxError" [ngxError]="{ name: 'Email'}" />
<ngx-validation-error [for]="email"></ngx-validation-error>
```

With a custom template:
```html
<input formControlName="password" #password="ngxError" [ngxError]="{ name: 'Password'}" />
<ngx-validation-error [for]="password">
  <ng-template #customProjectTemplate let-error="error">
    <div class="my-error">
      <i class="fa fa-exclamation-circle"></i> {{ error }}
    </div>
  </ng-template>
</ngx-validation-error>
```

Global registration of a custom template via `ErrorTemplateRegistry` can apply to all instances.  

To register a template globally you can capture a template reference in a component and then pass it to the registry after view initialization. For example:

```ts
import { AfterViewInit, Component, TemplateRef, ViewChild } from '@angular/core';
import { ErrorTemplateRegistry } from 'ngx-field-validation-errors';

@Component({/* ... */})
export class AppComponent implements AfterViewInit {
  @ViewChild('globalCustomErrorTemplate') public errorTemplate!: TemplateRef<any>;

  constructor(private errorTemplateService: ErrorTemplateRegistry) {}

  ngAfterViewInit(): void {
    // registers the template for use by name
    this.errorTemplateService.setErrorUiTemplate(this.errorTemplate);
  }
}
```

```html
<ng-template #globalCustomErrorTemplate let-error="error">
  <div class="error-text">{{error}} ❗</div>
</ng-template>
```

Once registered, every `<ngx-validation-error>` or `ngx-error` field that requests the corresponding template will render using the shared markup.

---

## 📚 Resources

- Angular forms guide: https://angular.io/guide/forms-overview
- Angular CLI: https://angular.io/cli

---

## 📜 License

MIT © NgxFieldValidationErrors

## 👤 Creator

- **Name:** Shantanu Yewale
- **Email:** shantanuyewale12345@gmail.com  
  _(Feel free to share any bugs or feedback.)_
- **LinkedIn:** https://www.linkedin.com/in/shantanu-yewale-53a044212/
- **Portfolio:** https://shantanuyewaledev.netlify.app/

---

*Thanks for using NgxFieldValidationErrors! Contributions and issues are welcome.*
