The following method is for old AngularJS:
Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:
<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
<label class="col-sm-2 control-label" for="username">Username*</label>
<div class="col-sm-10 col-md-9">
<input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
</div>
</div>
It is also important, that your form has the ng-submit=""
attribute:
<form name="myForm" ng-submit="checkSubmit()" novalidate>
<!-- input fields here -->
....
<button type="submit">Submit</button>
</form>
You can also add an optional function for validation to the form:
//within your controller (some extras...)
$scope.checkSubmit = function () {
if ($scope.myForm.$valid) {
alert('All good...'); //next step!
}
else {
alert('Not all fields valid! Do something...');
}
}
Now, when you load your app the class 'has-error'
will only be added when the form is submitted or the field has been touched.
Instead of:
!myForm.username.$pristine
You could also use:
myForm.username.$dirty
FOR NEW ANGULAR 2+
This based on Bootstrap 5.3 and Angular 15/16, could be changed in future.
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{'is-invalid': password?.errors != null}">
</div>
the component form, make sure that you have change the myForm
, into form variable you need.
get password() { return this.myForm.get("password") }