Angular has helpers that tell you if the form (or form field) is $dirty
(user typed something), or if the form $touched
(blur event was triggered on input). See this demo.
I only need to highlight the invalid fields after the first submission.
Unfortunately Angular doesn't support this. But you could implement this yourself pretty easily:
controller
function FormController() {
var vm = this;
vm.submitAttempted = false;
vm.submit = function(isValid) {
if (isValid) {
}
else {
vm.submitAttempted = true;
}
};
}
Html
<div ng-app='app'>
<div ng-controller='FormController as vm'>
<form name='fooForm' ng-submit='vm.submit(fooForm.$valid)' novalidate>
<label>Username</label>
<input
name='username'
type='text'
ng-model='vm.user.username'
required
ng-minlength='4'
ng-class="{'invalid': vm.submitAttempted && fooForm.username.$invalid}">
<br /><br />
<button type='submit'>Submit</button>
</form>
</div>
</div>
CSS
.invalid {
border-color: red;
}
Demo
I have a problem where the first time the page is loaded, it immediately displays a red border in the username field, even before I start typing anything.
Probably because you have the following CSS class:
.ng-invalid {
border-color: red;
}
Angular always applies the class ng-invalid
to invalid fields and there is nothing you can do about it. Therefore, if you do not always want invalid fields to have a red border, you cannot use this class, and you must do it as suggested above.
Also check out ngMessages .
source
to share