ngx-show-form-errors
v1.0.2
Published
An Angular library providing a directive to automatically display form error messages.
Downloads
8
Maintainers
Readme
NgxShowFormErrors
This is an Angular library, consisting of a directive to automatically display form error messages.
The library can be installed in your Angular application with the following command:npm install ngx-form-errors
To use the directive, you can apply it either to the form or directly to the input fields (it is not necessary to apply it to both). Example:
<form #form="ngForm" id="formId" ngxShowFormErrors>
<input type="text" name="fieldName" #fieldName [(ngModel)]="fieldValue" required maxlength="10" />
<div data-field="fieldName">
<div data-validator="required">required field message</div>
<div data-validator="maxlength">maxlength field message</div>
</div>
</form>Notice that below the field, you can declare a list of error messages. To do this, you must create a structure where there is a container with the data-field attribute, with the name of the field (in the case of Reactive Forms, use the value of formControlName), and inside it, a list of HTML elements with the validation text, where each validation is identified by the data-validator attribute, passing its type as the value.
Don't forget to import the directive in your module. Example:
import { ShowFormErrorsDirective } from 'ngx-show-form-errors';
imports: [
ReactiveFormsModule,
NgxShowFormErrorsDirective,
],The directive is compatible with both Reactive Forms and Template Driven Forms.
The initial state will not display any error messages until a blur event occurs on the field or until the form is submitted. If the form is submitted, all errors will be displayed.
What the directive does to display the errors is add classes to the field and the error message elements. The library does not create any CSS styles, so you will need to create your own styles according to the classes the directive adds to the elements. The classes added by the directive are the ones natively used by Bootstrap 5, so if you use Bootstrap, you won’t need to worry about this.
The directive automatically adds the .invalid-feedback class to the container with the error messages, and .invalid-feedback-item to each message element. In addition, it will also add the .d-none class to each message element if the state is valid, and also add the .is-invalid class to the field if the state is invalid.
An example style for this would be:
.is-invalid {
border: solid 1px red;
}
.invalid-feedback > .invalid-feedback-item {
color: red;
}
.invalid-feedback > .invalid-feedback-item.d-none {
display: none;
}