Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 41749  / 9 Years ago, wed, june 3, 2015, 12:00:00

HTML:



<div class=form-group 
ng-class={ 'has-error' : form.firstName.$invalid && form.firstName.$touched }>
<label for=firstName
class=control-label>
First Name
</label>
<input type=text
name=firstName
id=firstName
ng-model=editableUser.firstName
class=form-control
required>
<span class=help-block
ng-show=form.firstName.$error.required && form.firstName.$touched>
First Name is required
</span>
</div>

<input type=submit
ng-click=submit()
value=Submit
class=btn btn-default>


I'm trying to get my the 'has-error' class to kick in for invalid fields when a user clicks submit.



I would think you could do something like this:



$scope.submit = function () {
if ($scope.form.$invalid) {
angular.forEach($scope.form.$invalid, function(field) {
field.$setTouched();
});
alert(Form is invalid.);
}
};


But there is no $setTouched method in https://docs.angularjs.org/api/ng/type/form.FormController



EDIT: Realize $setTouched does exist, it's in https://docs.angularjs.org/api/ng/type/ngModel.NgModelController


More From » angularjs

 Answers
4
if ($scope.form.$invalid) {
angular.forEach($scope.form.$error, function (field) {
angular.forEach(field, function(errorField){
errorField.$setTouched();
})
});
alert(Form is invalid.);
}


plunker:
http://plnkr.co/edit/XmvoTkIQ0yvFukrVSz11


[#66341] Tuesday, June 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katieh

Total Points: 692
Total Questions: 104
Total Answers: 104

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;