Angular 2: custom validation with input formatting

I have a situation where I need format

to enter a user and then validate

.

I am using reactive form

and created mine custom validation

as shown below (relevant parts):

HTML:

<input type="text" formControlName="invoiceNumber" (blur)="formatInvoiceNumber()" class="form-control">
<div *ngIf="this.form.controls['invoiceNumber'].invalid && this.form.controls['invoiceNumber'].touched">Invalid Text</div>

      

Controller:

this.form = this.formBuilder.group({
            'invoiceNumber': ['', validateInvoiceNumber()],
        });

    formatRoNumber() {
            var invoiceNumber = this.form.controls['invoiceNumber'].value;
            //format invoice number
        }

      

Validator:

export function validateInvoiceNumber(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        let invoiceNumber = control.value,
            isValid = true;

        //validate invoice number
        return isValid ? null : { validInvoiceNumber: { valid: false } }
    };
}

      

I am having sync problems. Input formatting occurs after validation.

How can I say Angular

apply formatting

and then validate

?

+3


source to share


2 answers


You can do this with formbuilder if you also use ngModel for formatting. I did it like this

<ion-input
formControlName="fullName"
type="text"
[ngModel]="fullName | pipeHere"
(ngModelChange)="fullName=$event">
</ion-input>

this.customerFields = this.fb.group({
  fullName: ['', Validators.compose([ Validators.required, Validators.minLength(11) ])]
});

      



(ngModelChange) will be what fires in your pipe while the check is running normally. If you are writing a custom feed, you can also enable additional validation.

+1


source


For some reason, the caleb method doesn't work for me, and the validator is called twice as much.

If it helps anyone, I ended it like this. There must be a better way, it seems weird to install Validators, apply them and then remove them for the next updates ... but it works.

Thank you Caleb and Deborah for your help.

Control:



<input type="text" formControlName="invoiceNumber" (blur)="updateAndValidateInvoiceNumber()" class="form-control">

      

Controller:

updateAndValidateInvoiceNumber(): void {
     let control: AbstractControl = this.form.controls['invoiceNumber'];
     let newVal = this.invoiceFormatterPipe.transform(control.value);

     control.patchValue(newVal);
     control.setValidators(validateInvoiceNumber());
     control.updateValueAndValidity();
     control.clearValidators();
 }

      

0


source







All Articles