I used a template driven form for my login page. I want a red border on input elements if they are invalid or have any errors but the class borderRed
is not being added on an input element when the input is blank or invalid.
<form (ngSubmit)="f.form.valid && signin()" #f="ngForm" class="m-login__form m-form" action="">
<ng-template #alertSignin></ng-template>
<div class="form-group form-md-line-input form-md-floating-label">
<label>
Email <span class="text-danger">*</span>
</label>
<input [class.borderRed]="email.invalid" class="form-control m-input" type="text" required="required" name="email" [(ngModel)]="model.email" #email="ngModel" autocomplete="off">
</div>
<div class="form-group form-md-line-input form-md-floating-label">
<label [pTooltip]="attachementTooltipmsg" tooltipPosition="top" for="form_control_1">
Password <span class="text-danger">*</span>
</label>
<input [class.borderRed]="password.invalid" class="form-control m-input" required="" name="password" type="password" [(ngModel)]="model.password" #password="ngModel">
</div>
<div class="m-login__form-action">
<button [disabled]="loading" [ngClass]="{'m-loader m-loader--right m-loader--light': loading}" id="m_login_signin_submit" class="btn btn-focus m-btn m-btn--pill m-btn--custom m-btn--air">
Sign In
</button>
</div>
</form>
To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.
The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model.
Use this
<input [class.borderRed]="email.touched && !email.valid" class="form-control m-input" type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required name="email" [(ngModel)]="model.email" #email="ngModel" autocomplete="off">
Check out StackBiltz
Edited code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With