1.0.5 • Published 6 years ago

ngx-validation-plus v1.0.5

Weekly downloads
25
License
MIT
Repository
-
Last release
6 years ago

Ngx-validation- plus

This Package is compatible with angular >=5

This package helps handling display error messages on angular forms. The problem with validation messages in forms is that they will grow easily and make your markup file dirty and untidy.


Description

With this package instead of doing this:

<label for="name">Name</label>
<input type="text" id="name" class="form-control"
       required minlength="4" maxlength="24"
       name="name" formControlName="name">
<div *ngIf="name.errors && (name.dirty ||  name.touched)"  class="alert alert-danger">
    <div [hidden]="!name.errors.required">
      Name is required
    </div>
    <div [hidden]="!name.errors.minlength">
      Name must be at least 4 characters long.
    </div>
    <div [hidden]="!name.errors.maxlength">
      Name cannot be more than 24 characters long.
    </div>
</div>

you can use this one:

<label for="name">Name</label>
<input type="text" id="name" class="form-control"
       required minlength="4" maxlength="24"
       name="name" formControlName="name">
<div *ngIf="errors.has('name')" class="alert alert-danger">
  <p *ngFor="let err of errors.get('name')">{{err}}</p>
</div>

Installation

Install the npm module by running:

npm install ngx-validation-plus --save

Usage

The first step is just like every other external module:

1- import ValidationMessagesModule to your root module (which is usually called AppModule)

     import { ValidationMessagesModule } from "ngx-validation-plus";
     @NgModule({
       declarations:[...],
       imports:[
        ...,
        ValidationMessagesModule.forRoot()
        ],
        bootstrap:[...]
      })
      export class AppModule {}

In this way the module will use default configurations and if you want to customize it, you can add your provider right here. It will be described later in Customizing section.

2- Import ValidationMessagesService in components that you have defined your form there and use it like below:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MessageBag, ValidationMessagesService } from 'ngx-validation-plus';
@Component({
    selector: 'first-form',
    templateUrl: 'first-form.component.html'
})
export class FirstFormComponent implements OnInit {
errors: MessageBag = new MessageBag();
firstForm: FormGroup;

constructor(private fb: FormBuilder, private validationMessages: ValidationMessagesService) { }
    
ngOnInit(): void {
    this.buildForm();
}

buildForm(): void {
    this.firstForm = this.fb.group({
        'name': ['', [
            Validators.required,
            Validators.minLength(4),
            Validators.maxLength(24)
        ]]
    });

    this.validationMessages
        .seeForErrors(this.firstForm)
        .subscribe((errors: MessageBag) => {
            this.errors = errors;
        });
}
  

3- Use it in your template:

<lable for="name">Name</label>
<input type="text" id="name" class="form-control"
       required minlength="4" maxlength="24"
       name="name" formControlName="name">
<div *ngIf="errors.has('name')" class="alert alert-danger">
  <p *ngFor="let err of errors.get('name')">{{err}}</p>
</div>

Customizing

What we described before was just the simplest way to use this package but absolutely you need more than angular built-in validators and of course in most scenarios you want to use internationalization, so you probably use ngx-translate or i18n or your custom library for it. In order to provide the source of messages for package you must follow these steps:

1- Provide your custom implementation for MessageProvider class and it should provide 3 methods:

import { MessageProvider, ErrorFormatRule } from 'ngx-validation-plus';

class CustomProvider implements MessageProvider {
    getMessage(errorKey: string): string{
      //your custom implementation...
     }
 
    getAttribute(attribute: string): string{
      //your custom implementation...
     }
 
    getPlaceHolders(errorKey: string): ErrorFormatRule{
     //your custom implementation...
    }  
}

Let's clarify what each method does:

  • getMessage

    This is the method responsible to provide messages by their keys, let's say we have this messages in our .ts or .json file :

      {
       'required':'please fill :attribute field',

    'minLength':':attribute field must have at least :min character' }

    After validating a form, ValidationMessagesModule has error keys and need you to provide corresponding messages for them. Here is where you have to do it.

  • getAttribute

    As you can see in previous message examples, there is a :attribute in every message which is obviously the name of filed and you should consider having equivalent names in different languages or maybe just a more comprehensive word to show to user. Let's say we have this:

      {
       "email" : "email Address",
       "fName" : "First name"
      }

    This method is responsible to provide suitable substitute for field name and if it can't do that, it will use the field name itself.

  • getPlaceHolders

    In this example we had something else: :min

       'minLength':':attribute field must have at least :min character'

    This is a placeholder to prepare more information about error and this method is responsible to provide this information. As you can see in method signature, it must return an object of type ErrorFormatRule which is simply an interface:

       export interface ErrorFormatRule {
        errorKey: string;
        placeholders?: any;
         }

For this method you must extend this array with your own custom rules :

   export const PlaceHolders: ErrorFormatRule[] = [
     {
        errorKey: 'minlength',
        placeholders: {
            ':min': 'requiredLength'
        }
     },
     {
        errorKey: 'maxlength',
        placeholders: {
            ':max': 'requiredLength'
        }
     },
     { errorKey: 'required' },
     { errorKey: 'pattern' }
  ];

and then implement the method to use it . A simple implementation is provided here:

  public getPlaceHolders(errorKey: string): ErrorFormatRule | undefined {
      return PlaceHolders.find((x) => x.errorKey === errorKey);
  }

2- Now that you have everything done, it's time to tell module use it. You do this by introducing this CustomProvider to forRoot method of module:

@NgModule({
    imports: [
        // other imports..
        //construct with your params
        ValidationMessagesModule.forRoot({ messageProvider: {provide: MessageProvider, useClass: CustomProvider }}) 
    ]
})
export class AppModule{
}

And you're done!

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago