Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
    
ng-modal ??????????? –  underscore May 10 '14 at 11:18
    
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}" –  Mohit Kumat May 10 '14 at 11:25
    
Show some code, of what you are trying. –  Chandermani May 10 '14 at 12:03
    
@Chandermani Please refer updated code sample above. –  Mohit Kumat May 10 '14 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. –  Chandermani May 10 '14 at 12:17

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks @ExpertSystem, it worked. –  Mohit Kumat May 10 '14 at 14:26
    
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]. –  Mohit Bhansali Jul 4 '14 at 8:04
    
I have already answered your question in my answer :)If you face any specific issue, please post a question. –  ExpertSystem Jul 4 '14 at 9:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.