angularjsformsvalidationangular-ui-routernested-views

Ui router nested views: how to validate a shared form?


Available plunker here

I'm using angular ui-router nested views to implement a multi-step form (a kind of wizard) and I having troubles trying to validate the form. The form is shared in all nested views, but it seems to be that the validation only affects the nested view where the submit button is placed.

Nested views:

$stateProvider
    .state('form', {
        url: '/form',
        templateUrl: 'form.html',
        controller: 'formController'
    })

    .state('form.step1', {
        url: '/step1',
        templateUrl: 'form-step1.html'
    })

    .state('form.step2', {
        url: '/step2',
        templateUrl: 'form-step2.html'
    });

I have one required input in each nested view:

form-step1.html:

<input type="text" name="required1" ng-model="formData.required1" required>

form-step2.html:

<input type="text" name="required2" ng-model="formData.required2" required>

In this nested view (the last step of my wizard) I also have the submit button, disabled if the form is not valid:

<button ng-disabled="form.$invalid" ng-submit="submit">Submit</button>

Well, validation is working fine for the input of this view, but it's not keeping in mind the input of the previous view (form-step1.html). Since the form is the same for all views, I expect that input requrired1 should be also validated. However, although the input requrired1 is empty, the form is considered valid.

So, my question is: How could I validate a form keeping in mind the inputs of all nested views?

Thanks in advance for the help.


Solution

  • Well, after being thinking a while about this, I think the easiest choice here is to validate each form step (nested view) individually.

    So, until the form is valid for a determinated nested view (form-step1), the button to continue to the next step (form-step2) is showing disabled. If we do in this way, when we arrive to the last nested view (form-step2 in the OP case, wich contains the submit button), we have already validated all the previous form-steps. So, we just need to validate the form for the current nested view to guarantee that the whole form is valid.

    Updated form-step1.html:

    <div>
        <label for="required1">Required 1</label>
        <input type="text" name="required1" ng-model="formData.required1" required>
    </div>
    
    <div>
        <button ng-disabled="form.$invalid" ui-sref="form.step2" type="button">Next</button>
    </div>
    

    Updated plunker here.