Reputation: 93
I am using angularJS directive and i want to find each input whether it has any errors, for example: required or pattern is incorrect.
HTML:
<form validation name="loginForm" ng-submit="form(this)">
<label> example 1
<input type="text" name="firstname" ng-model="user.firstname" ng-model-options="{ updateOn: 'mousedown blur'}" required
ng-pattern="validationPatterns.firstname">
</label>
<label> example 2
<input type="text" name="lastname" ng-model="user.lastname" ng-model-options="{ updateOn: 'mousedown blur'}" required
ng-pattern="validationPatterns.lastname">
</label>
<button class="btn" type="submit">Continue</button>
</form>
Directive: This outputs the names of each input name ( firstname and lastname and it includes all the objects like $required, $errors, $invalid etc...)
element.find('button').on('click', function () {
var input = element.find('input');
angular.forEach(input, function (inputs) {
var inputName = $(inputs).attr('name');
console.log(scope.loginForm[inputName]);
});
});
Now how do I check each element input, for example:
if input[name].$error.required=== true, show an error message. I wanted to check this on the directive not the HTML
Upvotes: 0
Views: 419
Reputation: 161
You can do something like this:
<div class="input-group">
<label for="firstname">Firstname</label> <input name="firstname" type="text"
class="form-control input-sm" ng-model="user.firstname" required />
<span
ng-show="loginForm.firstname.$error.required && loginForm.firstname.$dirty">Required!
</span>
</div>
Hope this helps!
Upvotes: 0