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 want to apply the 'has-error' class to invalid fields when a user clicks submit.
This can be achieved by:
$scope.submit = function () {
if ($scope.form.$invalid) {
angular.forEach($scope.form.$invalid, function(field) {
field.$setTouched();
});
alert("Form is invalid.");
}
};
Initially, it was believed that $setTouched
method does not exist in https://docs.angularjs.org/api/ng/type/form.FormController
UPDATE: It has been confirmed that $setTouched
exists and is actually present in https://docs.angularjs.org/api/ng/type/ngModel.NgModelController