Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic validation and name in a form with AngularJS

Tags:

angularjs

I have this form : http://jsfiddle.net/dfJeN/

As you can see the name value for the input is statically set :

name="username" 

, the form validation works fine (add something and remove all text from the input, a text must appears).

Then I try to dynamically set the name value : http://jsfiddle.net/jNWB8/

name="{input.name}" 

Then I apply this to my validation

login.{{input.name}}.$error.required 

(this pattern will be used in an ng-repeat) but my form validation is broken. It is correctly interpreted in my browser (if I inspect the element I saw login.username.$error.required).

Any Idea ?

EDIT: After logging the scope in the console it appears that the

{{input.name}} 

expression is not interpolate. My form as an {{input.name}} attribute but no username.

UPDATE: Since 1.3.0-rc.3 name="{{input.name}}" works as expected. Please see #1404

like image 230
IxDay Avatar asked Jan 17 '13 11:01

IxDay


People also ask

Which method is used to add dynamic validation to the forms?

The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.

What is used for validating AngularJS forms?

AngularJS offers client-side form validation. AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also holds information about whether they have been touched, or modified, or not.

How is validation done in AngularJS?

AngularJS performs form validation on the client-side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.

What is dynamic validation?

In ASP.NET 3.5 a DynamicValidator was added. It basically "Enforces and catches exceptions that are thrown in a data model and displays the error."


1 Answers

You can't do what you're trying to do that way.

Assuming what you're trying to do is you need to dynamically add elements to a form, with something like an ng-repeat, you need to use nested ng-form to allow validation of those individual items:

<form name="outerForm"> <div ng-repeat="item in items">    <ng-form name="innerForm">       <input type="text" name="foo" ng-model="item.foo" />       <span ng-show="innerForm.foo.$error.required">required</span>    </ng-form> </div> <input type="submit" ng-disabled="outerForm.$invalid" /> </form> 

Sadly, it's just not a well-documented feature of Angular.

like image 196
Ben Lesh Avatar answered Sep 28 '22 10:09

Ben Lesh