[ngx-formly] Implement a custom form validator with Angular Formly

Formly comes with a lot of built-in validators. Nevertheless you most likely will have to to implement some custom validation. In this lesson we're going to do exactly that. Learn how to create a custom validator with Formly.

Implement a global IP validator:

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormControl, ValidationErrors } from '@angular/forms';
import { FormlyModule, FormlyFieldConfig } from '@ngx-formly/core';
import { FormlyMaterialModule } from '@ngx-formly/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { SharedModule } from './shared/shared.module';

// global min error message, you can override by validation.messages.min in field
export function minValidationMessage(err, field: FormlyFieldConfig) {
  return `Please provide a value bigger than ${err.min}. You provided ${err.actual}`;
}

export function ipValidationMessage(err, field: FormlyFieldConfig) {
  return `"${field.formControl.value}" is not a valid IP address`;
}

export function IpValidator(control: FormControl): ValidationErrors {
  return !control.value || /(\d{1,3}\.){3}\d{1,3}/.test(control.value) ? null : { ip: true };
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    SharedModule,
    ReactiveFormsModule,
    FormlyModule.forRoot({
      validators: [
        {
          name: 'ip',
          validation: IpValidator,
        },
      ],
      validationMessages: [
        {
          name: 'required',
          message: 'This field is required',
        },
        {
          name: 'min',
          message: minValidationMessage,
        },
        {
          name: 'ip',
          message: ipValidationMessage,
        },
      ],
    }),
    FormlyMaterialModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

app.component.ts:

    {
      key: 'ip',
      type: 'input',
      templateOptions: {
        required: true,
        label: 'IP Address',
      },
      validators: {
        validation: ['ip'],
      },
    },

Implement custom validation for feild:

    {
      key: 'ip',
      type: 'input',
      templateOptions: {
        required: true,
        label: 'IP Address',
      },
      validators: {
        // validation: ['ip']
        ip2: {
          expression: c => !c.value || /(\d{1,3}\.){3}\d{1,3}/.test(c.value),
          message: (errorr, field: FormlyFieldConfig) =>
            `"${field.formControl.value}" is not valid`,
        },
      },
    },