ngx-reactive-form-extensions
TypeScript icon, indicating that this package has built-in type declarations

2.1.8 • Public • Published

pipeline status coverage report

Reactive Form Extensions (ngx-reactive-form-extensions)

Table Of Contents

Basic Overview

The purpose of this project is to enhance the functionality of Angular's ReactiveForms by providing useful features. This is achieved through the use of various directives, each designed to address common issues such as trimming form inputs, displaying error messages for form fields, or modifying a form field's CSS class based on the presence of a violated validation rule. By simply adding the necessary directive to the form field, the desired behavior can be achieved. This project is lightweight, does not require any additional dependencies, and significantly reduces the amount of boilerplate code needed.

Installation

Angular Version Recommended Version
<= 15.x.x v1.0.4
16.x.x v2.0.8
>= 17.x.x v2.1.x

  1. Import the desired directive into the feature module in order to make the directive available to that module.
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    ShowValidationMessagesDirective,
    ChangeClassOnErrorDirective,
    TrimDirective
  ],
  providers: [
    ...
  ]
})
export class AppModule { }

Note: For versions 1.x.x you will need to import the NgxReactiveFormExtensionsModule into the feature module in order to make the exported directives available to that module.

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    NgxReactiveFormExtensionsModule,
  ],
  providers: [
    ...
  ]
})
export class AppModule { }
  1. Then simply add the desired directive to any reactive form field. See here for the list of directives currently provided.

Optional: Configure Global Defaults

Global configurations allow you to configure the default behaviour for each directive.

import { RfxConfig, RFX_CONFIG } from 'ngx-reactive-form-extensions';

// Define the desired default behavior for each directive. Note, you can exclude any directives that you either do not wish to modify or use.
const rfxConfig: RfxConfig = {
  showValidationMessages: {
    cssClass: 'error-text', // Default is ''
    validationTriggerCondition: 'touched' // Default is 'touched'
  },
  trim: {
    setEmptyValuesToNull: true // Default is true
  },
  changeClassOnError: {
    cssClass: 'is-invalid; // Default is ''
    validationTriggerCondition: 'touched' // Default is 'touched'
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    CommonModule
  ],
  providers: [
    { provide: RFX_CONFIG, useValue: rfxConfig }
  ]
  bootstrap: [AppComponent]
})
export class AppModule {}

RfxConfig

The RfxConfig interface has the following properties:

RfxConfig {
  showValidationMessages: {
    cssClass: string;
    validationTriggerCondition: 'touched' | 'dirty'
  }
  trim: {
    setEmptyValuesToNull: boolean
  }
  changeClassOnError: {
    cssClass: string;
    validationTriggerCondition: 'touched' | 'dirty'
  }
}

Directives

The following directives are currently available in this version:

Displaying ReactiveForm Validation Messages (showValidationMessages)

The showValidationMessages directive is designed to automatically display error messages associated with any broken validation rules below the invalid form field. Angular offers a variety of pre-built Validators," and this directive will display default messages for any Angular validators used in the form. For example, if a form control utilizes the Angular validator Validators.required, the message "This field is required" will be displayed below the form field when that validation rule is broken.

Validator Default Message
required This field is required.
min Value must be greater than or equal to ${MIN_VAL}.
max Value must be less than or equal to ${MAX_VAL}.
maxLength Value entered must be less than or equal to ${MAX_LENGTH} characters.
minLength Value entered must be greater than or equal to ${MIN_LENGTH} characters.
pattern Invalid Input.
email Invalid email.

Setting Custom Validator Messages

This project offers a validator class that wraps the pre-existing Angular validators and introduces some additional validators. By utilizing the validators from this class, you can provide an optional custom error message to any of the validations.

To get started with setting your custom validation messages, simply import the extended validators class, RfxValidators. Here's an example to guide you:

Using default Validator

const firstName = new FormControl(null, Validators.required);

Setting custom message

const firstName = new FormControl(null, RfxValidators.required('First name is required'));

Note: The validator class RfxValidators acts as a wrapper for the built in angular Validators, this means to perform the actual validations, the Angular Validator implementation of the rule will be executed under the hood. Using the RfxValidators class simply allows you to customize the error message that should be displayed.

Overriding the css class for the displayed validation message

You can override css class that should be applied to the validation message of a given form field by adding the property validationMessageClass="${some_css_classname}" to the form field. Eg

// TS
const form = new FormGroup(
  firstName: new FormControl(null, Validators.required)
);

// HTML
<form [formGroup]="form">
  <input type="text" formControlName="firstName" class="form-control" validationMessageClass="is-invalid-custom">
</form>

Additional properties

Additional attributes that can be added to the form field to further configure the directive. Note using these attributes will override any global defaults

Attributes Values Description
validationMessageClass string The name of the css class to be applied to the validation message that will be displayed.
validationTriggerCondition touched / dirty The condition that should trigger the display of the validation message. The validation message will only be displayed once the condition is met, regardless of the error state. I.e if the condition is set as touched then the validation message will only be displayed once the field has been touched.

Changing the form field CSS on error (changeClassOnError)

This directive changeClassOnError allows you to configure the css class that should be applied to the field, as well as the event that should trigger the change, i.e touched or dirty.

Example

// TS
const form = new FormGroup(
  firstName: new FormControl(null, Validators.required)
);

// HTML
<form [formGroup]="form">
  <input type="text" formControlName="firstName" class="form-control" changeClassOnError>
</form>

Additional properties

Additional attributes that can be added to the form field to further configure the directive. Note using these attributes will override any global defaults

Attributes Values Description
errorClass string The name of the css class to be applied when the field is in an error state
validationTriggerCondition touched / dirty The condition that should trigger the class change. This class will only be changed once the condition is met, regardless of the error state. i.e if the condition is set as touched then the class will only be changed once the field has been touched.

Trimming & Formatting Inputs

This directive trim simply trim leading and trailing spaces from string/text inputs. Optionally, this directive can be configured to convert empty strings to null.

Sample

// TS
const form = new FormGroup(
  firstName: new FormControl(null, Validators.required)
);

// HTML
<form [formGroup]="form">
  <input type="text" formControlName="firstName" class="form-control" trim>
</form>

Additional properties

Additional attributes that can be added to the form field to further configure the directive. Note using these attributes will override any global defaults

Attributes Values Description
setEmptyToNull true / false Toggles the feature which converts empty field values to null.

Additional Validators

fieldMatch

Validator that requires that the input for both fields specified are equal. The error message appear under the two fields specified. Eg use-case: Validating that passwords match.
This validator must be added at the form group level.
Note: Both fields must be of the same data type for accurate matching.

  • Default Message: Value for ${field1} does not match ${field2}.
Parameter Data type Description Required
field1 string The form control name of field 1. true
field2 string The form control name of field 2. true
message string The error message that should be displayed. false

passwordComplexity

Validator that requires the control's value to contain atleast 1 lowercase, uppercase, digit and special character.\

  • Default Message: Password must contain atleast 1 lowercase, uppercase, digit and a special character.
Parameter Data type Description Required
message string The error message that should be displayed. false

dateAfter

Date validator which validates that the input is a date that occurs after the date specified.
Note: For best results ensure that the field input value is of type Date or a date string.

  • Default Message: Date entered must be greater than ${FORMATTED_DATE}.
Parameter Data type Description Required
date Date or valid date string The date to compare the input against. true
message string The error message that should be displayed. false

dateBefore

Date validator which validates that the input is a date that occurs before the date specified.
Note: For best results ensure that the field input value is of type Date or a date string.

  • Default Message: Date entered must be greater than ${FORMATTED_DATE}.
Parameter Data type Description Required
date Date or valid date string The date to compare the input against. true
message string The error message that should be displayed. false

# Additional Utilities This project currently exports the following utility functions:
  1. removeFormControlError(control: AbstractControl, errorName: string)
    Removes the specified error from the form control passed.
  • Parameters
    • control - The form control
    • errorName - The name of the error to remove
  1. appendFormControlError(control: AbstractControl, errorName: string, errorMessage: string)
    Appends an error to a form control
  • Parameters
    • control - The form control.
    • errorName - The name of the error to append.
    • errorMessage - A custom error message.

Basic Example

This example will demonstrate the following:

  • Ensure that our validations messages will be displayed below each invalid form field.
  • Trim string inputs and convert empty values to null
  • Add a css class to the form field whenever the form field is in an error state. This css class will turn the field borders red providing feedback to the user that there is an error.
  • Ensure that the css class is only added to the form field when the field has been touched.

Importing the form extensions module and configuring the directives globally

const rfxConfig: RfxConfig = {
  showValidationMessages: {
    cssClass: 'error-text',
    validationTriggerCondition: 'touched'
  },
  trim: {
    setEmptyValuesToNull: true
  },
  changeClassOnError: {
    cssClass: 'is-invalid',
    validationTriggerCondition: 'touched'
  }
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    ShowValidationMessagesDirective,
    ChangeClassOnErrorDirective,
    TrimDirective
  ],
  providers: [{ provide: RFX_CONFIG, useValue: rfxConfig }]
  bootstrap: [AppComponent]
})
export class AppModule { }

Building the FormGroup

This form represents a simple form where we capture the user's name and email and allow them to set a password. To better ensure that the user has entered the correct password, we require them to enter it twice. That said, we need to validate that the values entered for password and passwordConfirm are the same. We can use the Validator provided in this project RfxValidators.fieldMatch to do just that!. We will also make use of another built in validator RfxValidators.passwordComplexity to ensure that the password contains atleast 1 lowercase, uppercase, digit and a special character.

const form = new FormGroup({
  firstName: new FormControl(null, [Validators.required, Validators.maxLength(30)]),
  lastName: new FormControl(null, [Validators.required, Validators.maxLength(30)]),
  email: new FormControl(null, [Validators.required, Validators.email]),
  password: new FormControl(null, [Validators.required, RfxValidators.passwordComplexity()]),
  passwordConfirm: new FormControl(null, Validators.required),
});
this.form.addValidators(RfxValidators.fieldMatch('password', 'passwordConfirm', 'Passwords do not match.'));

HTML Form

<form [formGroup]="form">
  <label>First Name</label>
  <input type="text" formControlName="firstName" trim showValidationMessages changeClassOnError />

  <label>Last Name</label>
  <input type="text" formControlName="lastName" trim showValidationMessages changeClassOnError />

  <label>Email</label>
  <input type="email" formControlName="email" trim showValidationMessages changeClassOnError />

  <label>Password</label>
  <input type="password" formControlName="password" trim showValidationMessages changeClassOnError />

  <label>Confirm Password</label>
  <input type="password" formControlName="passwordConfirm" trim showValidationMessages changeClassOnError />
</form>

Package Sidebar

Install

npm i ngx-reactive-form-extensions

Weekly Downloads

5

Version

2.1.8

License

MIT

Unpacked Size

259 kB

Total Files

31

Last publish

Collaborators

  • riuen