2

Im new to AngularJS and i have problem using HTML5 nested form validation properly.

I have 2 forms one is mainFrm (parent form) and the other is stateFrm (a child form). I have problem validating each form on its own scope.

<form id="mainFrm" ng-submit="save()">

    <text-input form="mainFrm" required type="text">

    <form id="stateFrm" ng-submit="addState()">

        <input form="stateFrm" type="text">

        <!-- this wont add an item if input-text is empty--> 
        <!-- prompts html5 validation-->  
        <button form="stateFrm" type="submit">Add state to favorite</button>

        <!-- and a list of favorite states -->

    </form>

    <!-- (Will validate only the text-input of mainFrm if empty) -->
    <button type="submit">Save</button>
</form>

When doing this the submit button of stateFrm doesnt work. the ng-submit="" of that form wont trigger and there is no validation prompting when input is empty.

Here is the working DEMO

NOTE: I used angular-material design

Shift 'n Tab
  • 8,808
  • 12
  • 73
  • 117

2 Answers2

3

While nested forms aren't allowed in HTML5, you can separate the forms while keeping the same layout. Check the codepen here for a working example: http://codepen.io/anon/pen/YNrGrp

<form id="mainFrm" name="mainFrm" layout="column" ng-submit="vm.saveMain()">
  <md-input-container>
    <label for="name">Group name</label>
    <input type="text" required ng-model="group" />
  </md-input-container>
</form>

<form layout="column" name="stateFrm" layout-align="start" id="stateFrm" ng-submit="vm.addItem(state)">
  <md-input-container>
    <input required form="stateFrm" type="text" ng-model="state" aria-label="state item" placeholder="enter state"/>
  </md-input-container>
  <md-button form="stateFrm" class="md-raised" type="submit">Add state to favorite</md-button>

  <md-list>
    <md-subheader>Favorite States</md-subheader>
    <md-list-item ng-repeat="state in vm.states | orderBy">
      <span class="md-body-1">{{ state }}</span>
    </md-list-item>
  </md-list>
</form>


<md-button form="mainFrm" class="md-raised md-primary" type="submit">Save Main</md-button>
Fissio
  • 3,748
  • 16
  • 31
1

As per W3C HTML5 Documentation, nested forms are not valid/allowed.

Santanu Biswas
  • 4,699
  • 2
  • 22
  • 21