简体   繁体   中英

Custom validation in Angular template-driven form does not update form state

I'm trying to write a custom validator for a template-driven form. The validator itself (included below) works like a charm for field-level validation. But it does not update the validation state for the entire form. In other words, when all controls are valid, the form tag still shows class="ng-invalid".

When I remove the phoneValidator from the control in my template, everything works fine.

I'm wondering if this might have something to do with the registerOnValidatorChange method that's defined in the interface. I'm not specifically implementing this in my custom validator, but I'm also not quite sure how to use it:

export interface Validator {
    validate(c: AbstractControl): ValidationErrors | null;
    registerOnValidatorChange?(fn: () => void): void;
}

Thoughts appreciated. Thanks!

file: phonevalidator.directive.ts:

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidationErrors, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[validPhoneNumber]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi:     true }
  ]
})
export class PhoneValidatorDirective implements Validator {

  validate(control: FormControl): ValidationErrors | null {
    return PhoneValidatorDirective.validatePhone(control);
  }

  static validatePhone(control: FormControl): ValidationErrors | null {

    var regEx = new RegExp(/^[1-9]\d{2}-\d{3}-\d{4}/);

    console.log("Phone validator: validating phone number.")

    var controlValue: string = control.value;

    console.log(regEx.exec(controlValue));

    if (!(regEx.exec(controlValue))) {
      // Return error if phone number is not valid
      console.log('returning false');
      return { phoneNumber: false };
    } else {
      // If no error, return null
      console.log('returning true');
      return { phoneNumber: true };
    }

  }
}

... looks like this was a duplicate of Angular 2 form status is always invalid with custom validation for ng-select control .

The answer is that validator must return null if control is valid, not true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM