我创建了以下 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],
});