簡體   English   中英

如何在通用驗證器類angular2中實現自定義驗證器?

[英]How to implement custom validator in generic validator class angular2?

我正在嘗試將自定義驗證器實現到通用驗證器類中,基本上我知道要在純類中編寫普通的自定義驗證器,但是在編寫通用驗證器類時會遇到一些困惑。 如果有人知道,請幫幫我。

這是我的generic-validator.ts文件

 import { FormGroup } from '@angular/forms'; // Generic validator for Reactive forms // Implemented as a class, not a service, so it can retain state for multiple forms. export class GenericValidator { // Provide the set of valid validation messages // Stucture: // controlName1: { // validationRuleName1: 'Validation Message.', // validationRuleName2: 'Validation Message.' // }, // controlName2: { // validationRuleName1: 'Validation Message.', // validationRuleName2: 'Validation Message.' // } constructor(private validationMessages: { [key: string]: { [key: string]: string } }) { } // Processes each control within a FormGroup // And returns a set of validation messages to display // Structure // controlName1: 'Validation Message.', // controlName2: 'Validation Message.' processMessages(container: FormGroup): { [key: string]: string } { let messages = {}; for (let controlKey in container.controls) { if (container.controls.hasOwnProperty(controlKey)) { let c = container.controls[controlKey]; // If it is a FormGroup, process its child controls. if (c instanceof FormGroup) { let childMessages = this.processMessages(c); Object.assign(messages, childMessages); } else { // Only validate if there are validation messages for the control if (this.validationMessages[controlKey]) { messages[controlKey] = ''; if ((c.dirty || c.touched) && c.errors) { for (let messageKey in c.errors) { if (c.errors.hasOwnProperty(messageKey) && this.validationMessages[controlKey][messageKey]) { messages[controlKey] += this.validationMessages[controlKey][messageKey]; } } } } } } } return messages; } } 

這是我用於自定義驗證程序的參數,即:'22,3333,4,555,66',[2,5]第一個是逗號分隔的字符串...可能有2或5個長條目,這里的條件是每個逗號化名的字符串必須> 2。

當我編寫自定義驗證器時,通常將其與反應形式一起使用。 我的自定義驗證器位於從@ angular / forms模塊擴展驗證器的類中。 這樣,如果驗證成功,則返回null;如果驗證不好,則返回對象。以下檢查無效字符。

import { FormControl, Validators, ValidatorFn } from '@angular/forms';

// setup simple regex for white listed characters
const validCharacters = /[^\s\w,.:&\/()+%'`@-]/;

// create your class that extends the angular validator class
export class CustomValidators extends Validators {

 // create a static method for your validation
 static invalidateCharacters(control: FormControl) {

    // first check if the control has a value
    if (control.value && control.value.length > 0) {

      // match the control value against the regular expression
      const matches = control.value.match(invalidCharacters);

      // if there are matches return an object, else return null.
      return matches && matches.length ? { invalid_characters: matches } : null;
    } else {
      return null;
    }
  }
}

創建一個FormErrorService來構建您的錯誤消息:

import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Injectable()
export class FormErrorService {

  // return list of error messages
  public validationMessages() {
    const messages = {
      required: 'This field is required',
      email: 'This email address is invalid',
      is1980OrLater: 'Please enter a date that is after 01/01/1980.',
      maxDateFailed: (failText: string) => {
        return failText;
      },
      minDateFailed: (failText: string) => {
        return failText;
      },
      invalid_characters: (matches: any[]) => {

        let matchedCharacters = matches;

        matchedCharacters = matchedCharacters.reduce((characterString, character, index) => {
          let string = characterString;
          string += character;

          if (matchedCharacters.length !== index + 1) {
            string += ', ';
          }

          return string;
        }, '');

        return `These characters are not allowed: ${matchedCharacters}`;
      },
    };

    return messages;
  }

  // Validate form instance
  // check_dirty true will only emit errors if the field is touched
  // check_dirty false will check all fields independent of
  // being touched or not. Use this as the last check before submitting
  public validateForm(formToValidate: FormGroup, formErrors: any, checkDirty?: boolean) {
    const form = formToValidate;

    for (const field in formErrors) {
      if (field) {
        formErrors[field] = '';
        const control = form.get(field);

        const messages = this.validationMessages();
        if (control && !control.valid) {
          if (!checkDirty || (control.dirty || control.touched)) {
            for (const key in control.errors) {
              if (key && key !== 'invalid_characters') {
                formErrors[field] = formErrors[field] || messages[key];
              } else {
                formErrors[field] = formErrors[field] || messages[key](control.errors[key]);
              }
            }
          }
        }
      }
    }
    return formErrors;
  }
}

在您的組件中構建表單的位置:

    import {CustomValidators} from 'filepath';
    import {FormErrorService} from 'formerrorservicepath';
    myFormGroup: FormGroup;
    public formErrors = {
    myInput: ''
  };
  formErrors = [];
  constructor(
    public formErrorService: FormErrorService
  ) {}
    // then in your ngOnInit 
    this.myFormGroup = new FormGroup({});
    this.myFormGroup.addControl('myInput', new FormControl());
    this.myFormGroup.get('myInput').setValidators(Validators.compose([CustomValidators.invalidCharacters]);

this.myFormGroup.valueChanges.subscribe(data => {
      this.formErrors = [];
        this.formErrors = this.formErrorService.validateForm(
          this.myFormGroup,
          this.formErrors,
          true
        );
      })

現在在您的HTML中:

<form [formGroup]="myFormGroup">
<div>
<input type="text" formControlName="myInput"/>
<p *ngFor="let error of formErrors">
{{error}}
</p>
<button type="button" [diabled]="!myFormGroup.valid">Action Button</button>
</div>
</form>

您可以嘗試一個名為ts.validator.fluent的框架。 通用對象驗證。 流利的規則。

https://github.com/VeritasSoftware/ts.validator

NPM套件

https://www.npmjs.com/package/ts.validator.fluent

還有一個Angular 6 CLI應用程序來演示框架:

https://github.com/VeritasSoftware/ts-validator-app-angular6

這是如何使用框架驗證TypeScript模型的示例:

/* Install npm package ts.validator.fluent and then import like below */
import { IValidator, Validator, ValidationResult } from 'ts.validator.fluent/dist';

/*TypeScript model*/
class Person {
   Name: string;
}

/* Validation rules */
var validatePersonRules = (validator: IValidator<Person>) : ValidationResult => {
   return validator
       .NotEmpty(m => m.Name, "Name cannot be empty")
   .ToResult();
};

/* Populate model */
var person = new Person();
person.Name = "John Doe";

/* Validate model */
/* Sync */
var validationResult = new Validator(person).Validate(validatePersonRules);
/* Async */
var validationResult = await new Validator(person).ValidateAsync(validatePersonRules);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM