I have a data driven form in angular2 like below
this.formBuilder.group({ 'name': ['',Validators.required], 'description': ['', Validators.required], 'places': this.formBuilder.array([], Validators.minlength(1)) })
I want to add validations to the place
formArray, so i am adding minlength
validation, but minlength validation is not working on formArray.
What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.
Validating Angular FormArray First you need to add the required validators while creating a new product form group inside the addProduct method. Now let's add a span element adjacent to the input control. Add the following CSS to the app. component.
FormArray setValue() setValue() sets the value of the FormArray . We need to pass an array that matches the structure of the control. Create a sample FormArray . myFormArray = new FormArray([ new FormControl(), new FormControl(), new FormControl() ]);
First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.
Validators.required
does the magic for you:
// using required this.formGroup = this.formBuilder.group({ taskTreeId: [Common.UID()], executionProgrammedTime: ["", [Validators.required]], description: [""], tasks: this.formBuilder.array([], Validators.required) }); // using custom validation export const minLengthArray = (min: number) => { return (c: AbstractControl): {[key: string]: any} => { if (c.value.length >= min) return null; return { MinLengthArray: true}; } } this.formGroup = this.formBuilder.group({ taskTreeId: [Common.UID()], executionProgrammedTime: ["", [Validators.required]], description: [""], tasks: this.formBuilder.array([], minLengthArray(2)) });
<button type="button" class="btn btn-success btn-rounded" [disabled]="!formGroup.valid">SAVE</button>
Add this custom validator to your validation service:
minLengthArray(min: number) { return (c: AbstractControl): {[key: string]: any} => { if (c.value.length >= min) return null; return { 'minLengthArray': {valid: false }}; } }
And then when creating the form do the following:
this.formBuilder.group({ 'name': ['',Validators.required], 'description': ['', Validators.required], 'places': this.formBuilder.array([], this.validationService.minLengthArray(1)) });
And you can check errors against the FormArray
by checking FormArray.hasError('minLengthArray')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With