Reputation: 1644
I have validation error styling and error messages, I have problem when submitting the form. The error messages are shown but the styling doesn't work.
input.ng-invalid.ng-touched
{
border: 1px solid #d70000;
color: #d70000;
}
<input type="text" class="form-control" [ngModelOptions]="{ updateOn: 'blur' }" [(ngModel)]="trip.city" id="city" #city="ngModel" required name="city">
As you can see above, I have the required attributed attached to the field. But the styling is working only when the field is touched (as you can see from the styling).
Full template:
<form class="form_step_wrapper" (ngSubmit)="onSubmit(f1)" #f1="ngForm" novalidate>
<div class="form_box">
<div class="step_form form-horizontal">
<section class="npc_box active">
<div class="form-group">
<label class="control-label" for="city">City</label>
<input type="text" class="form-control"
[ngModelOptions]="{ updateOn: 'blur' }" [(ngModel)]="trip.city" id="city"
#city="ngModel" required name="city">
<div *ngIf="city.errors && (city.touched || f1.submitted)">
<div class="error_message" *ngIf="city.errors?.required">
<span class="e_arrow"></span>
<i>Please enter city</i>
</div>
</div>
</div>
</section>
</div>
<div class="np_box">
<button class="next_step">Continue<i></i></button>
<div class="clear"></div>
</div>
</div>
</form>
I need to apply styling also when submitting, any idea what should I change/add? Thanks.
Upvotes: 0
Views: 75
Reputation: 18973
You can validate your input as below, you can customize error color in css file of component.
<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" name="city" [(ngModel)]="model.city" #city="ngModel" [ngClass]="{ 'is-invalid': f.submitted && city.invalid }" required />
<div *ngIf="f.submitted && city.invalid" class="invalid-feedback">
<div *ngIf="city.errors.required">City is required</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
https://stackblitz.com/edit/angular-template-ngmodel-validate
I update with your updated code
You need add (ngSubmit)="f.form.valid && onSubmit()"
to your HTML
https://stackblitz.com/edit/angular-template-ngmodel-validate-kjvs6r
Upvotes: 0
Reputation: 28738
It seems to me that setting the template variable name to "city" is causing the error, because it's a reserved word. Changing it will resolve the issue:
HTML
<input type="text" class="form-control" [ngModelOptions]="{ updateOn: 'blur' }"
[(ngModel)]="trip.city" id="city" #city2="ngModel" required name="city">
Upvotes: 0