0

have a simple dynamically generated form

  this.submitForm = this._fb.group({
          'tournamentid': new FormControl(null),
          'participants': this._fb.array([  ],   [CustomValidators.uniqueBy('nric'), this.averageAgeValidator(45)])
        });

Add Players event will dynamically add below code

     addPlayers(): FormGroup {
            return this._fb.group({
                 'nric': new FormControl(null, [Validators.required]),
                  'nricname': new FormControl(null, Validators.required),
                  'dob': new FormControl(null, Validators.required),

            });
          }

I want to validate if average DOB of all the dynamically added form fields is 45 years. have function to calculate age, and i have a date component to get dates. need to know how to loop through the formarrays and get only the dob fields and get average of it.

how should my averageAgeValidator function work to flag error when the average age of all the added players is 45 years. please suggest

4
  • Are you showing some calendar to select DOB ? and then accordingly calculate age ? Or is it some <input type="number" /> type thing ? Commented Feb 17, 2019 at 11:44
  • @ShashankVivek i missed that part, age calculation is available and its a date component. my issues is just the validation assuming i have the date. looping through the formarray and picking only the dob values. Commented Feb 17, 2019 at 13:12
  • Did u try something like what I have put in answer ? Commented Feb 18, 2019 at 9:31
  • did you get a solution for this?@SquaplRecipes Commented Apr 26, 2019 at 7:00

2 Answers 2

4

I added custom validators in reactive forms and it worked for me.

Form Definition, where partnerEmailArray is an array of emails, and partnerEmail is a field with custom validations.

createPartnerForm() {
this.createPartnerForm = this.partnerFormBuilder.group({
  partnerName: new FormControl({}, Validators.required),
  partnerEmailArray: this.partnerFormBuilder.array([this.partnerFormBuilder.group({
    partnerEmail: [{}, [Validators.required, this.emailValidator(this.re)]]
  })])
})

Validator function

emailValidator(emailRe: RegExp): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
  const email = emailRe.test(control.value);
  return email ? null : { 'CustomEmail': { value: control.value } };
};

}

getting the form and form array

 get Partnerform() {
return this.createPartnerForm.controls;  }
get PartnerformEmail() {
return this.createPartnerForm.get('partnerEmailArray') as FormArray;}

and in html,

<label>Email address</label>
        <div class="email" formArrayName="partnerEmailArray">
          <div *ngFor="let item of PartnerformEmail.controls; let $index=index" [formGroupName]="$index">
            <input type="text" class="form-text form-control" id="email"
                   formControlName="partnerEmail">                
            <div *ngIf="Partnerform.partnerEmailArray.controls[$index].controls.partnerEmail.touched && Partnerform.partnerEmailArray.controls[$index].controls.partnerEmail.errors">
              <div *ngIf="Partnerform.partnerEmailArray.controls[$index].controls.partnerEmail.errors.required" class="validationMessage">
                Partner Email is required.
              </div>
              <div *ngIf="!Partnerform.partnerEmailArray.controls[$index].controls.partnerEmail.errors.required && Partnerform.partnerEmailArray.controls[$index].controls.partnerEmail.errors.CustomEmail" class="validationMessage">
                Partner Email is invalid.
              </div>
            </div>
          </div>

        </div>
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried custom validators ?

'dob': new FormControl(null, [Validators.required,this.customValidator]),

customValidatorForUrl (control: AbstractControl) {
  // you can acccess value using "control.value"
  // do the calculation and return true\false as per your calculation
  return true/false;
}

2 Comments

can you provide the html binding for form array custom validations?
@AkshayAntony : share me your question link. I'll try to answer it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.