我创建了以下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);
}
}
使用mask伪指令输入(掩码有效,但由于无法处理输入值,验证停止工作):
<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],
});
答案 0 :(得分: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);
}
}