Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Form Validation Directive $setValidity on element

I'm trying to use $setValidity on an element in a directive. All the examples I've found seem to set it on the controller...

I forked a JS fiddle on Form Validation and have tried a bunch of things. Any insights would be most appreciated: http://jsfiddle.net/thomporter/pmKpG/2/

In the fiddle, the $setValidity is called on the controller:

ctrl.$setValidity('pwd', true);

I'd like to do something like:

elm.$setValidity('pwd', true);

so that in the form I can do something like:

ng-class="{error:form.password.$error.pwd}"
like image 619
Thom Porter Avatar asked Mar 25 '13 12:03

Thom Porter


People also ask

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.

How do you check whether a form is valid or not in AngularJS?

The form instance can optionally be published into the scope using the name attribute. So to check form validity, you can check value of $scope. yourformname. $valid property of scope.

How do you apply validations in AngularJS forms explain with proper example?

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.

What is $dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.


1 Answers

I figured it out... You have to have a name on the input elements. As soon as I added the name, the errors were automatically bound to the elements as desired, no additional changes needed!

<input ng-model="password"
       name="inputPassword"
       class="immediate-help"
       password-validate
       required
       type="password"
       id="inputPassword"
       placeholder="Password">

http://jsfiddle.net/thomporter/pmKpG/4/

like image 186
Thom Porter Avatar answered Oct 18 '22 01:10

Thom Porter