Angular reactive forms add custom Validation onBlur

Discussão em 'Angular' iniciado por jhon.smith, Abril 17, 2025.

  1. jhon.smith

    jhon.smith Guest

    I am trying to get the OnBlur syntax correct but it is eluding me.

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    published: true,
    credentials: this.fb.array([]),
    });
    }

    addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
    username: ['', [this.isNameDuplicate(this.form)]],
    password: '',
    }));
    }

    isNameDuplicate(form:FormGroup): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
    const userNames = this.form.get("credentials").value;
    console.log(userNames);
    const names = userNames.map(item=> item.username.trim());
    const hasDuplicate = names.some(
    (name, index) => names.indexOf(name, index + 1) != -1
    );

    if (hasDuplicate) {
    console.log(hasDuplicate);
    return { duplicate: true };
    }

    return null;
    }
    }
    }


    I have to make sure that the isNameDuplicate validator fires onblur but the syntax is eluding me.

    Can i get some help please.

    My try

    addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.fb.group({
    username: ['', {
    validators:[this.isNameDuplicate(this.form)],
    updateOn:'blur'}],
    password: '',
    }));
    }


    But i get an error saying isNameDuplicate does not exist on the component.

    Continue reading...

Compartilhe esta Página