Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs get form field validity inside directive

Tags:

I'm hoping this isn't a duplicate - plenty of similar questions about but I can't find an answer that works.

I have an Angular directive, thus:

app.directive('emailInput', function(){     return {         restrict: 'E',         templateUrl: 'template.html',         link: function(scope, elem, attrs, ctrl){             elem.bind('keyup', function(){                 // TODO - what?             })         }     } } 

and in the template html:

<input type="email" required ng-model="emailAddress" /> 

Without knowing the name of the form, inside the link function, I want to know the value of the emailAddress.$valid property - how can I get this?

like image 475
Greg Smith Avatar asked Oct 16 '13 21:10

Greg Smith


People also ask

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.

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.

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.

Which of the following methods would you use to check if a specific field is empty or not in a form in AngularJS?

You could also use ng-hide="somefield. length" instead of ng-show="!


1 Answers

You can require the formController which would give you access to all of the inputs registered to the form

app.directive('emailInput', function(){   return {       require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.       restrict: 'E',       templateUrl: 'template.html',       link: function(scope, elem, attrs, ctrl){           elem.bind('keyup', function(){               ctrl.emailAddress.$valid //check validity           })       }   } } 

Remember that Angular keeps track of input elements by name. So you have to give your input a name attribute

<input type="email" required ng-model="emailAddress" name="emailAddress" /> 

I would also recommend possibly just passing all of this through a directive attribute. You probably don't want to hard code the field names. So you could just have an attribute that takes the validity

inputIsValid='formName.emailAddress.$valid' 

And evaluate (or $watch it) in your directive.

like image 89
Adam Avatar answered Nov 06 '22 17:11

Adam