npm package: @ngserveio/validation-messages
Description: Find more at libraries and examples at [NgServe.io](https://ngserve.io).
Author: Paul Mead
Latest version: 10.0.0

# @ngserveio/validation-messages

Find more at libraries and examples at [NgServe.io](https://ngserve.io).

This library was generated with [Nx](https://nx.dev).

## Purpose

The validation messages project alleviates developers from writing bloated markup for validation messages through a the `ngServeValidationDisplay` directive.

[1]: https://www.youtube.com/watch?v=I0djwBCf4LU
[2]: https://img.youtube.com/vi/I0djwBCf4LU/mqdefault.jpg

### See the Video Tutorial on YouTube

[![Angular Reactive Forms Validation with @ngserveio/validation-messages][2]][1]

## Running unit tests

Run `nx test shared-ui-validation-display` to execute the unit tests.

## Configuration

Import the module `NgServeValidationDisplayModule` into the consuming module.

```ts
@NgModule({
  imports: [NgServeValidationDisplayModule],
})
export class SampleModule {}
```

### ValidationMessageService

The `ValidationMessageService` ships with default validation messages.

```ts
export const ValidationMessages: { [key: string]: string } = {
  required: '{{fieldName}} is required.',
  email: '{{fieldName}} is invalid.',
  minlength: 'Minimum length is {{requiredLength}}',
  maxlength: 'Maximum length is {{requiredLength}}',
  min: '{{fieldName}} is less than minimum value of {{min}}.',
  max: '{{fieldName}} exceeds maximum value of {{max}}.',
  uniqueEmail: '{{value}} is already taken',
  exists: '{{fieldName}} {{value}} does not exist',
  agreeToTerms: 'You must agree to our terms.',
  url: '{{fieldName}} has invalid url',
  alphanumeric: '{{fieldName}} must be alphanumeric characters.',
  unique: '{{fieldName}} exists and must be unique.',
  isNumeric: '{{fieldName}} must be a numeric value',
};
```

The validation messages consist of the `key` being a validation and string being a message template. The message template creates consistency for form validation messages.

Each `key` maps to a key on a [FormControl's](https://angular.io/api/forms/FormControl) [errors](https://angular.io/api/forms/ValidationErrors) property.

The `errors` property implements a type of `{ [key:string]: any }`, so validation errors can supply more information. e.g. [min](https://angular.io/api/forms/Validators#static-methods) supplies the properties of `min` and `actual`.

To override these messages, use the `addMessages` method on the `ValidationMessgeService`.

#### Adding Messages

```ts
import { ValidationMessageService } from '@ngserveio/validation-display';

@NgModule({})
export class SampleModule() {
  constructor(private validationMessageService: ValidationMessageService) {
    validationMessageService.addMessages({
      min: '{{fieldName}} must be less than {{min}}.  {{actual}} was entered',
      isBetween: '{{fieldName}} must be between {{min}} and {{max}}.',
      required: 'Please enter a {{fieldName}}.'
    });
  }
}

```

## ValidationDisplayDirective

The validation display directive alleviates the need to bloat html markup in form. In order to display the validation message, add the `ngServeValidationDisplay` providing the control and `fieldName`. The `fieldName` will be supplied as part of the message if the message template includes it.

**Component Markup**

```html
<div [formGroup]="myForm">
  <label>Email</label>
  <input type="email" formControlName="email">
  <span [ngServeValidationDisplay]="emailControl" fieldName="Email">
</div>

```

**Component Code**

```ts
@Component({
  template: './sample.component.html',
})
export class SampleComponent {
  public myForm = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
  });

  public get emailControl(): AbstractControl {
    return this.myForm.get('email');
  }
}
```

## Validators

The following validators are also shipped in this package.

### emptyOrWhiteSpace

Checks if the control has a value that isn't white space. This will return `{ required: true }` if invalid, so it will use the `required` message template.

### isNumeric

Checks if the value is numeric. Returns `{ isNumeric: true }` using the `isNumeric` message template.

### requiredIf

Uses a predicate check on the condition supplied and checks if controls' value is empty or whitespace.

```ts
public sampleForm = new FormGroup({
  email: new FormControl('', [
    requiredIf((ctrl: AbstractControl) => {
      const siblingControl = ctrl.parent.get('sibling');
      return siblingControl.value;
    }
  ])
});
```