2

How to track input field validation within form without using field name or field name as array e.g. user[user_name]?

Sample Code:

<div ng-class="{ 'has-error' : saveUserForm.user[first_name].$invalid && !saveUserForm.user[first_name].$pristine }">
   <input type="text" value="{{userAttr.first_name}}" required ng-model="userAttr.first_name" name="user[first_name]" id="inputFirstName">
</div>

Using array name "user[first_name]" for form field is not working, and I can not change it to simple name like "firstName".

Can I use id of the field "inputFirstName" here: saveUserForm.inputFirstName.$invalid ?

4
  • BTW it is ng-model. But I don't want to track its value, I need to track if the field is valid or not so that I can add error class to the field e.g. ng-class="{error: userForm.userName.$invalid}" Commented May 10, 2014 at 11:25
  • Show some code, of what you are trying. Commented May 10, 2014 at 12:03
  • @Chandermani Please refer updated code sample above. Commented May 10, 2014 at 12:12
  • Name is required as it is used to create ngModelController. Also i don't think you can give an expression in the name. Commented May 10, 2014 at 12:17

1 Answer 1

1

The name attribute is required*, but Angular is not peeky about the name. It is OK if the name is user[first_name], as long as it is referenced correctly.

Assuming a name like this: name="user[first_name]"
You should reference it like this: saveUserForm['user[first_name]'].$...

E.g.

<div ng-class="{'has-error':saveUserForm['user[first_name]'].$invalid&&
                            !saveUserForm['user[first_name]'].$pristine}">

See, also, this short demo.


A little explanation:
In JavaScript saveUserForm.user[first_name] is equivalent to a[b] where a = saveUserForm.user and b = first_name


*: You might be able to get away with using no name, by creating a custom directive, get hold of the parent form's FormController and add the elements using its $addControl() method, but there is really no need to.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey. Is there is any way to validate form without using name attribute. I don't know, if I add name="objectvo.fieldname", by default I am getting [object object].
I have already answered your question in my answer :)If you face any specific issue, please post a question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.