• Stars
    star
    470
  • Rank 93,164 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A declarative validation errors module for reactive forms.

Build Status Dependency Status devDependency Status npm

ngx-errors

A declarative validation errors module for reactive forms.




Overview

Why use ngx-errors, how to install and use.

What is it?

Declarative validation error messages for reactive forms.

Typically you'd do something like this:

<!-- without ngxErrors -->
<input type="text" formControlName="foo">

<div *ngIf="form.get('foo').hasError('required') && form.get('foo').touched">
  Field is required
</div>
<div *ngIf="form.get('foo').hasError('minlength') && form.get('foo').dirty">
  Min length is 5
</div>

With ngxErrors, we've taken a simple declarative approach that cleans up your templates to make validation easier:

<!-- with ngxErrors -->
<input type="text" formControlName="foo">

<div ngxErrors="foo">
  <div ngxError="required" when="touched">
    Field is required
  </div>
  <div ngxError="minlength" when="dirty">
    Min length is 5
  </div>
</div>

Check out the documentation below for all the syntax we provide.

Installation

yarn add @ultimate/ngxerrors

# OR

npm i @ultimate/ngxerrors

Setup

Just add ngx-errors to your module:

import { NgxErrorsModule } from '@ultimate/ngxerrors';

@NgModule({ imports: [ NgxErrorsModule ] })

Documentation

ngxErrors

The ngxErrors directive works by dynamically fetching your FormControl under-the-hood, so simply take your formControlName value and pass it into ngxErrors:

<input type="text" formControlName="username">
<div ngxErrors="username">
  // ...
</div>

This needs to be on a parent container that will encapsulate child ngxError directives.

ngxError

The ngxError directive takes either a string or array as arguments. The argument you pass in corresponds to any active errors exposed on your control, such as "required" or "minlength":

<input type="text" formControlName="username">
<div ngxErrors="username">
  <div ngxError="minlength">
    Min length is 5
  </div>
</div>

Note: when using array syntax, [] bindings are needed

Using the array syntax, when any condition in the array is true the error will be shown:

<input type="text" formControlName="username">
<div ngxErrors="username">
  <div [ngxError]="['minlength', 'maxlength']">
    Min length is 5, max length is 10
  </div>
</div>

ngxError #when

The when directive takes either a string or array as arguments. It allows you to specify when you wish to display the error based on the control state, such as "dirty" or "touched":

<input type="text" formControlName="username">
<div ngxErrors="username">
  <div ngxError="minlength" when="dirty">
    Min length is 5
  </div>
</div>

It also comes in array format for multiple rules:

<input type="text" formControlName="username">
<div ngxErrors="username">
  <div ngxError="minlength" [when]="['dirty', 'touched']">
    Min length is 5
  </div>
</div>

Dynamic errors

You can optionally data-bind and dynamically create validation errors with ngxErrors:

<input type="text" formControlName="username">
<div ngxErrors="person.username">
  <div *ngFor="let error of errors" [ngxError]="error.name" [when]="error.rules">
    {{ error.text }}
  </div>
</div>

With corresponding component class:

@Component({...})
export class MyComponent {
  errors = [
    { name: 'required', text: 'This field is required', rules: ['touched', 'dirty'] },
    { name: 'minlength', text: 'Min length is 5', rules: ['dirty'] }
  ];
}

Nested FormGroup support

ngxErrors also supports FormGroups with control names using dot notation:

<div formGroupName="person">
  <input type="text" formControlName="username">
  <div ngxErrors="person.username">
    <div ngxError="minlength" [when]="['dirty', 'touched']">
      Min length is 5
    </div>
  </div>
</div>

Exported Directive API

ngx-errors exports itself as ngxErrors, which means you can access information about your control error states elsewhere in your template using a template reference, such as #foo.

Basic usage:

<div ngxErrors="username" #myError="ngxErrors"></div>

getError(name: string): any;

The getError method returns the object associated with your error. This can be useful for dynamically displaying error rules.

Example: Adds Min length is 5 when value is less than 5 characters (based on Validators.minLength(5)).

<input type="text" formControlName="username">

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="minlength" when="dirty">
    Min length should be {{ myError.getError('minlength')?.requiredLength }}
  </div>
</div>

The error returned is identical to Angular's FormControl API

hasError(name: string, conditions?: string | string[]): boolean;

The hasError method informs you if your control has the given error. This can be useful for styling elsewhere in your template based off the control's error state.

Example: Adds class="required" when "myError" has the required error.

<div [class.required]="myError.hasError('required')">
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

You can optionally pass in conditions in which to activate the error.

Example: Adds class="required" when "myError" has the required error and the states are 'dirty' and 'touched'.

<div [class.required]="myError.hasError('required', ['dirty', 'touched'])">
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

You can also use the "catch-all" selector to get the state of your entire control's validity, alongside on an optional state collection.

<div>
  <div [ngClass]="{
    invalid: myError.hasError('*'),
    invalidTouchedDirty: myError.hasError('*', ['touched', 'dirty'])
  }">
  </div>
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

isValid(name: string, conditions?: string | string[]): boolean;

The isValid method informs you if a your control is valid, or a property is valid. This can be useful for styling elsewhere in your template based off the control's validity state.

Example: Adds class="valid" when "myError" has no required error.

<div [class.valid]="myError.isValid('required')">
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

You can optionally pass in conditions in which to evaluate alongside the property you're checking is valid.

Example: Adds class="valid" when "myError" has no required error and the states are 'dirty' and 'touched'.

<div [class.valid]="myError.isValid('required', ['dirty', 'touched'])">
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

You can also use the "catch-all" selector to check if the control is valid, with no specific error properties, alongside on an optional state collection.

<div>
  <div [ngClass]="{
    valid: myError.isValid('*'),
    validTouchedDirty: myError.isValid('*', ['touched', 'dirty'])
  }">
  </div>
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
</div>

hasErrors: boolean;

The hasErrors property returns true if your control has any number of errors. This can be useful for styling elsewhere in your template on a global control level rather than individual errors.

Example: Adds class="errors" when "myError" has any errors.

<div [class.errors]="myError.hasErrors">
  <input type="text" formControlName="username">
</div>

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="required" when="dirty">
    Field is required
  </div>
  <div ngxError="minlength" when="dirty">
    Min length is 5
  </div>
</div>

errors: { [key: string]: any; };

The errors property returns the object associated with any active errors. This can be used to access any error properties on your control.

Example: Adds Max length is 10, you typed (n) when value is more than 10 characters (based on Validators.maxLength(10)).

<input type="text" formControlName="username">

<div ngxErrors="username" #myError="ngxErrors">
  <div ngxError="minlength" when="dirty">...</div>
  <div ngxError="maxlength" when="dirty">...</div>
</div>

<div *ngIf="myError.errors?.maxlength">
  Max length is 10, you typed {{ myError.errors.maxlength.actualLength }}
</div>

The errors returned are identical to Angular's FormControl API

Contributing

Please see the contributing guidelines.

More Repositories

1

angular-pro-src

Source code for the "Angular Pro" course.
TypeScript
335
star
2

angular-fundamentals-src

Source code for the "Angular Fundamentals" course.
TypeScript
252
star
3

vault

Typed localStorage and sessionStorage utility with data structure and prefix support.
TypeScript
178
star
4

redux-store

Vanilla TypeScript example of a Redux Store
TypeScript
169
star
5

angular-fundamentals-seed

Angular Fundamentals seed project
JavaScript
143
star
6

angular-pro-app-seed

Seed project for Angular Pro final application
JavaScript
107
star
7

angular-tesla-range-calculator

Building Tesla's battery range calculator with Angular 2+ reactive forms
TypeScript
96
star
8

javascript-basics

πŸ† Starter project for JavaScript Basics
CSS
83
star
9

ultimate-angular-master-seed

Seed project for the "Ultimate Angular 1.x Pro" course.
JavaScript
73
star
10

typescript-masterclass-src

TypeScript Masterclass. Advanced TypeScript, comprehensively covered in real-world digestable chapters.
TypeScript
72
star
11

angular-lazy-load-demo

Lazy loading: code-splitting with @​NgModules demo
TypeScript
69
star
12

ultimate-angular-master-src

Source code for "Ultimate Angular 1.x Pro" course material
JavaScript
62
star
13

typescript-basics-seed

Seed project for TypeScript Basics course
HTML
56
star
14

ultimate-angular-starter-src

Source code for "Ultimate Angular 1.x Fundamentals" course:
HTML
55
star
15

typescript-basics-src

TypeScript Basics. Our comprehensive introduction to static types in JavaScript.
JavaScript
53
star
16

lite-store

Reactive Stores with entities and frozen state, without the headache
TypeScript
49
star
17

ultimate-angular-starter-seed

The starter project for the "Ultimate Angular 1.x Fundamentals" course
CSS
38
star
18

ngx-fullscreen

Angular Directive that implements the Fullscreen API.
TypeScript
35
star
19

node-express-typescript

A minimal starter project to write your Node.js apps in TypeScript, complete with local and production build scripts.
TypeScript
35
star
20

angular-1-performance-src

Source code for AngularJS Performance course
JavaScript
30
star
21

javascript-masterclass

πŸ† Starter project for JavaScript Masterclass
CSS
24
star
22

javascript-html5-apis

πŸ† Starter project for JavaScript HTML5 APIs
JavaScript
20
star
23

javascript-dom

πŸ† Starter project for the JavaScript DOM course
CSS
18
star
24

ngx-pagevisibility

TypeScript
15
star
25

angular-basics-src

TypeScript
15
star
26

javascript-dom-project

πŸ† Starter project for the JavaScript DOM course project build
CSS
14
star
27

react-basics

πŸ† Starter project for React Basics [Create React App]
JavaScript
14
star
28

angular-basics-seed

Angular Basics (v15) Course Seed Project
TypeScript
12
star
29

typescript-masterclass-seed

Seed project for TypeScript Masterclass course
JavaScript
10
star
30

html-css-basics

πŸ† Starter project for the HTML + CSS Basics course
CSS
10
star
31

ultimate-react-icecream

UltimateCourses demo React app
JavaScript
10
star
32

rxjs-basics

πŸ† Starter project for RxJS Basics and Masterclass courses
CSS
9
star
33

react-router-src

JavaScript
7
star
34

react-state-management-course

JavaScript
6
star
35

react-router-seed

Learn React Router v6 🧭
JavaScript
5
star
36

react-basics-src

Source code for React Basics
JavaScript
4
star