1

I am developing Job form where user can enter his hobbies in the Job Form. I have applied required validation on hobbyName formcontrol, but how can I validate hobby name which should be unique if there is more than one hobby.

Below is my ts code

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormArray,FormBuilder,Validators } from "@angular/forms"
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  jobForm:FormGroup
  constructor(private jobfb:FormBuilder){}

  ngOnInit(){
    this.jobForm = this.jobfb.group({
      hobbies:this.jobfb.array([
        this.createHobbyFormGroup()
      ])
    })
  }

  addHobby(){
    let hobbies = this.jobForm.controls.hobbies as FormArray;
    hobbies.push(this.createHobbyFormGroup());
  }

  

  createHobbyFormGroup(){
    return this.jobfb.group({
      hobbyName:['',Validators.required]
    });
  }

}

below is my Html code

<button (click)="addHobby()">Add Hobby</button>
<table>
  <tr [formGroup]="hobbyFG" *ngFor="let hobbyFG of jobForm.controls.hobbies.controls;">
    <input formControlName="hobbyName"/>
  </tr>
</table>
<button [disabled]="!jobForm.valid">Submit</button>

whenever user click on add button, at that time new FormGroup will be added in the FormArray.

I am not able to figure out how can I validate the hobby name, which should be unique?

Please guide.

1

2 Answers 2

2

Ok,you can use RxwebValidators package,I have implemented it its working.Shared below my code.

In ts file(import in app module)

    import { RxwebValidators } from '@rxweb/reactive-form-validators';

    export class ProductComponent implements OnInit ,Product {
    public complexForm: FormGroup = this.builder.group({
    'firstName' : ['',[Validators.required,Validators.pattern('^[a-zA-Z0-9]+$')]],
      'lastName': ['', Validators.minLength(5)],
      hobbies:this.builder.array([
        this.createHobbyFormGroup()
      ]),
      'gender' : 'Female',
      'hiking' : false,
      'running' : false,
      'swimming' : false
    });

    addHobby(){
    let hobbies = this.complexForm.controls.hobbies as FormArray;
    hobbies.push(this.createHobbyFormGroup());
  }

  createHobbyFormGroup(){
    return this.builder.group({
      hobbyName:['',RxwebValidators.unique()]
    });
  }



 }

In Html

    <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">hobby Name</th>
    </tr>
  </thead>
  <tbody>
    <tr [formGroup]="skillGroup" *ngFor="let skillGroup of complexForm.controls.hobbies.controls;let i = index;">
      <th scope="row">{{i+ 1}}</th>
      <td><input type="text" formControlName="hobbyName" class="form-control"  />
    </tr>
  </tbody>
</table>
  <div class="form-group">
    <label>hobbies</label>
    <input class="form-control" type="text" [formControl]="complexForm.controls['hobbies']">
  </div>

I hope it will be helpful :)

Sign up to request clarification or add additional context in comments.

3 Comments

this validator doesn't work for looping an array and setting in FormArray
you can check by clicking on the abc button in this link stackblitz.com/edit/…
this works well but the only problem is the dependency that has to be used. Its size is almost 4mb which could be problmatic. Instead I have tried to solve the problem by using custom validator
0

I have created a custom validator which will check if there is any duplicate hobby that user has entered and if it finds duplicate then it returns the validation error.

Here is the stackblitz link for the same.

Note: I have created custom validator inside the component itself. But you can have a separate ts file for the same.

If there is anything that I missed please let me know I would be happy to help

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.