0

I have a FormGroup inside a form. I need to validate the FormGroup controls when I click the submit button, but it is not triggering. TransactionForm is the form and allocationForm is the FormGroup. I need to validate the FormGroup lone when clicking add button ie. required field validation is not triggering.

component.ts

this.transactionForm = this.fb.group({
  allocationForm: this.fb.group({
    fund: new FormControl(['', Validators.required]),
    amount: new FormControl(['', Validators.required]),
  })
});

html

<form novalidate *ngIf="transactionForm" [formGroup]="transactionForm" (ngSubmit)="submitTransaction()">
  <div class="form-group">
    <label for="name">name:</label>
    <input type="text" class="form-control" formControlName="name">
    <br/>
  </div>
  <fieldset formGroupName="allocationForm">
    <div class="form-group row">
      <label for="amount" class="col-lg-4 col-form-label">    {{labels.percent}}</label>
      <div class="col-lg-8">
        <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>
        <div class="form-control-feedback" *ngIf="errors.amount">
          errors.amount
        </div>
      </div>
    </div>
    <div class="form-group row">
      <div class="offset-lg-4 col-lg-8">
        <button type="button" class="btn btn-secondary" class="form-control" name="addButton" type="submit">Add</button>
      </div>
    </div>
  </fieldset>
</form>
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Palani
  • 9
  • 5
  • Your question is a bit unclear. At first, from where did this `errors` come from? I believe you want to write `transactionForm.get('allocationForm.amount').errors`. Also, to trigger the submit `function` you should change the type of button => ` – developer033 Jul 07 '17 at 21:28

1 Answers1

0

In your code at line

     <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>

After this in the div tag you are using wrong condition, It should be *ngIf="name.errors.<>", example: *ngIf="amount.errors.min". Hope it helps

  • what I need to do on add button click event to get required field validation triggered – Palani Jul 05 '17 at 15:28
  • Ok, you can do one thing, add a click event handler to your button click and in your component add a function to check for validations. Have one boolean variable which can enable or disable your add button with respect to validations. Have you got your answer ? – Parwinder Singh Jul 05 '17 at 15:52
  • I need the all the validation rules that's get executed automatically if I click on Add button. – Palani Jul 05 '17 at 15:55
  • Yes adding function for validation in your component will execute your validations only when you click add button. – Parwinder Singh Jul 06 '17 at 09:37