1

I am trying to validate an auto-generated form (via AngularJS v1.3) which inputs' names are in format:

form_name[field_name]

The very basic example would be:

<form name="morgageCalculator">
        <input type="text" class="form-control" 
            name="morgageCalculator[homeValue]" value="0"
            data-ng-model="data.homeValue" required="required"/>
</form>

As you can see, the input name is morgageCalculator[homeValue]. Now I would like to add an error message below it:

<div class="error"
     data-ng-show="!morgageCalculator.morgageCalculator[homeValue].$pristine && morgageCalculator.morgageCalculator[homeValue].$invalid">
    Please enter a number
</div>

For very obvious syntax reasons this expression is not valid:

morgageCalculator.morgageCalculator[homeValue].$pristine

But this one also does not work:

morgageCalculator["morgageCalculator[homeValue]"].$pristine

So, the question, is there any sane way of accessing those fields? I wouldn't mind moving the validation to some controller function, but I was faced with same issue of inability to access field object.

Any help/hint would be greatly appreciated.

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85
  • Could you refer this answer http://stackoverflow.com/a/28146946/2435473 would help you – Pankaj Parkar Dec 09 '15 at 20:26
  • The thing is, the form is not generated from within `AngularJS`, but in `Symfony` PHP framework, so the names are correct... – Jovan Perovic Dec 09 '15 at 20:40
  • 1
    It should be `data-ng-show="!morgageCalculator['morgageCalculator[homeValue]'].$pristine && morgageCalculator['morgageCalculator[homeValue]'].$invalid"` – dfsq Dec 09 '15 at 20:41
  • @JovanPerovic name attribute should have interpolation `ng-attr-name="{{morgageCalculator[homeValue]}}"` – Pankaj Parkar Dec 09 '15 at 20:42
  • @dfsq That is the correct syntax. In fact, due to copy/pastes, I somehow left out `data-ng-model` attribute. After adding it back, everything started working :) Thanks! – Jovan Perovic Dec 09 '15 at 20:54
  • @PankajParkar No, I have no desire to resolve names client-side... – Jovan Perovic Dec 09 '15 at 20:56

1 Answers1

1

With help of @dfsq from comment section, I was able to find the error. Unlike my SO question, my code was missing data-ng-model.

Validation will not fire at all if input was not bound to model....

The correct snippet:

<form name="morgageCalculator">
    <input type="text" class="form-control" 
        name="morgageCalculator[homeValue]" value="0"
        data-ng-model="data.homeValue" required="required"/>


    <div class="error"
        data-ng-show="!morgageCalculator['morgageCalculator[homeValue]'].$pristine && morgageCalculator['morgageCalculator[homeValue]'].$invalid">
            Please enter a number
    </div>
</form>
Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85