zoukankan      html  css  js  c++  java
  • [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`,
            },
          },
        },
  • 相关阅读:
    JUC-ThreadPool线程池
    JUC-JUC强大的辅助类讲解(Semaphore、CyclicBarrier、CountDownLatch)
    JUC—Callable接口
    集合与数组之间相互转化
    [UnityShader基础]07.MaterialPropertyDrawer
    [UnityShader基础]06.#pragma multi_compile
    [Unity优化]UI优化(三):GraphicRebuild
    [UnityAPI]SerializedObject类 & SerializedProperty类
    [Unity算法]点是否在多边形范围内
    [UGUI]圆形Image
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12172956.html
Copyright © 2011-2022 走看看