Пользовательский угловой валидатор конфликтует с маской ввода
Я создал следующий валидатор 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],
});
1 ответ
Я решил это, изменив директиву следующим образом ( https://github.com/RobinHerbots/Inputmask/issues/1317)
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);
}
}