0

我创建了以下 Angular 5 验证器:

import {AbstractControl} from '@angular/forms';
import * as cpf from '@fnando/cpf';

export class Validador {

    static cpf(control: AbstractControl): { [key: string]: any } {
        // https://github.com/fnando/cpf
        return cpf.isValid(control.value) ? null : {cpfInvalido: true};
    }
}

这个验证器工作得很好,除非我将它与应用输入掩码的自定义指令一起使用(https://github.com/RobinHerbots/Inputmask)。

该指令如下:

import {Directive, ElementRef, Input, OnInit} from '@angular/core';

declare var Inputmask;
@Directive({
  selector: '[mascara]'
})
export class MascaraDirective implements OnInit {

    @Input() mascara: any;
    constructor(private element: ElementRef) { }

    ngOnInit() {
        Inputmask({ // https://github.com/RobinHerbots/Inputmask
            mask: this.mascara,
            skipOptionalPartCharacter: ' '
        }).mask(this.element.nativeElement);
    }
}

使用掩码指令输入(掩码有效,但验证停止工作,因为无法处理输入值):

<input type="text" class="form-control" placeholder="CPF" formControlName="cpf" mascara="999.999.999-99">

有什么问题?

编辑:

添加表单构建器:

this.personForm = this.fb.group({
  name: ['', Validators.required],
  cpf: ['', [Validators.required, Validador.cpf]],
  phone: ['', Validators.required],
  email: ['', [Validators.required, Validators.email, Validators.pattern('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')]],
  password: ['', Validators.required],
  addressStreet: ['', Validators.required],
  addressNumber: ['', Validators.required],
  addressZipcode: ['', Validators.required],
  addressNeighborhood: ['', Validators.required],
  addressObservation: ['', Validators.required],
  idState: [null, Validators.required],
  addressCity: ['', Validators.required],
});
4

1 回答 1

0

我通过如下更改指令来解决它(https://github.com/RobinHerbots/Inputmask/issues/1317#issuecomment-341872101

import {Directive, ElementRef, Input, OnChanges, Optional} from '@angular/core';
import {NgControl} from '@angular/forms';
import * as _ from 'lodash';

declare var Inputmask;
@Directive({
  selector: '[mascara]'
})
export class MascaraDirective implements OnChanges {

    @Input() mascara: any;
    @Input('mascaraParams') options: any;
    constructor(private element: ElementRef, @Optional() private control: NgControl) { }

    ngOnChanges(): void { 
        if (!this.control) {
            console.warn('No control for InputMaskDirective');
            return;
        }

        if (this.mascara) {
            const options: any = _.clone(this.options) || {};
            _.defaults(options, { showMaskOnHover: false });
            options.oncomplete = options.onincomplete = options.oncleared = () => this.handleChange();
            Inputmask(this.mascara, options).mask(this.element.nativeElement);
        } else {
            Inputmask.remove(this.element.nativeElement);
        }
    }

    private handleChange(): void {
        this.control.control.patchValue(this.element.nativeElement.value);
    }
}
于 2018-10-05T16:19:35.673 回答