Giridhar Bandi
Giridhar Bandi

Reputation: 1323

Angular form validation with name in square brackets

For some reason I am unable to get the form element when it has a [] in the name. for example when I try the following

    <input class="form-control col-md-1" type="text" name="first_name" id="user_signup_last_name" placeholder="First name" ng-model="user.first_name" required >
    <span style="color:red" ng-show="myForm.last.$dirty && myForm.first_name.$invalid">
    <span class="col-md-1" ng-show="myForm.first_name.$error.required">First name required.</span>

But when I try changing the name to have [] the validation stops working.

    <input class="form-control col-md-1" type="text" name="user[first_name]" id="first_name" placeholder="First name" ng-model="user.first_name" required>
  <span style="color:red" ng-show="myForm.user[first_name].$dirty && myForm.user[first_name].$invalid">
  <span class="col-md-1" ng-show="myForm.user[first_name].$error.required">First name required.</span>
  1. How do we do get angular to validate on the name attribute with [] ?
  2. is there a way we can use id instead of name to check the validation?

Upvotes: 1

Views: 1859

Answers (2)

Tyrone Wilson
Tyrone Wilson

Reputation: 4618

Came across this issue today and the "escaping solution" didn't work for me.

In essence the form submission for rails works with [] but the ng-messages directive doesn't play well with this.

I created a directive that uses a pseudo-name attribute to handle the form stuff leaving the name attribute free for rails nested attribute syntax (in CoffeeScript)

angular.module 'myModule'
  .directive 'fieldName', ->
    directive =
      restrict: 'A'
      require: ['ngModel', '^form']
      scope:
        fieldName: '@fieldName'
      link: (scope, elem, attrs, controllers) ->
        modelCtrl = controllers[0]
        formCtrl = controllers[1]

        formCtrl[scope.fieldName] = modelCtrl
        return

To use this directive then I used the following (in haml)

%label My label
%input(ng-model='user_account.email' name='user_account[email]' required field-name='email' required type='email')
%div(ng-messages='form.email.$error')
    %span(ng-message='required') Required

Upvotes: 0

Dvir
Dvir

Reputation: 3339

You can access the property by {{formName['user[first_name]'].$error}}

Upvotes: 1

Related Questions