Unique value validator for angular2 formGroup

443 Views Asked by At

I am using angular reactive formsGroup and formControl. my requirement is the value of each formControl should be unique and if user try to add duplicate value then it should show validation error.

FormGroup Creation

 this.contryCodeForm = this.formBuilder.group({
            US: ['+1', , [],[this.uniqueValidator, Validators.required]],
            UK: ['+44',  [],[this.uniqueValidator, Validators.required]],
            India: ['+91', [],[this.uniqueValidator, Validators.required]],
            email: ['+61', [],[this.uniqueValidator, Validators.required]]
        });]

I want to add validation if any one try to edit the value which already taken by other country.

enter image description here

I have tried to implement the this.uniqueValidator

const values = Object.keys(formGroup.value).map(key => formGroup.value[key])

const filtered = values.filter(x=>x === control.value); 
if (filtered.length > 1) {
return {message: "This field must be unique value"}
}

but it does not work

any help appreciated

1

There are 1 best solutions below

0
erst_dev On

I think you should do this:

  1. Create validator, which takes formGroup
export class MyOwnValidator {
    
    static checkDuplicates(formGroup: FormGroup): ValidationErrors | null {
        //here you can get access to all controls 
          and implement the logic for checking duplicates
    }
}

  1. Add this validator in formGroup
this.contryCodeForm = this.formBuilder.group({
            US: ['+1', , [],[ Validators.required]],
            UK: ['+44',  [],[ Validators.required]],
            India: ['+91', [],[Validators.required]],
            email: ['+61', [],[Validators.required]]
        }, , {
            validators: MyOwnValidator.checkDuplicates
        })