Reputation: 3019
I have created a form in which i applied ngclass to show error when form value is not given, unfortunately it shows error when the form gets loaded for the first time.
So by default when the form is loaded my input tag is in-valid, so it is showing error, i am not sure what to do.
Can someone help me pls.
My html,
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin adminloginform" novalidate>
<label class="col-sm-4 text-right norightpadding">First Name</label>
<div class="input-group" [ngClass]="{errmsg: !form.controls['lastname'].valid }" >
<input type="text" [formControl]="form.controls['lastname']" >
</div>
<div class="col-sm-8">
<button type="submit" >Register now</button>
</div>
My ts,
export class SignUp {
constructor(public fbld: FormBuilder, http: Http, public config: Config, public router: Router) {
this.http = http;
this.form = fbld.group({
firstname: ['', Validators.required],
});
this.header = this.config.header1;
}
onSubmit(form: ISignup): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json')
this.http.post(this.header + 'signup', form, { headers: headers })
.subscribe(
response => {
if (response.json().error_code == 0) {
this.router.navigate(['/login']);
}
else {
console.log(response.json().message);
}
});
}
my css,
.errmsg{
border: 1px solid red;
}
Upvotes: 0
Views: 7308
Reputation: 55443
Just add pristine
as shown,
[ngClass]="{errmsg: (!form.controls['lastname'].valid &&
!form.controls['lastname'].pristine)}"
Show validation only when form is submitted for this please check below plunker.
https://plnkr.co/edit/mJFftirG3ATDpnJRWmKN?p=preview
Upvotes: 2
Reputation: 86750
try this code
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin adminloginform" novalidate>
<label class="col-sm-4 text-right norightpadding">First Name</label>
<div class="input-group" [ngClass]="{'errmsg': !form.controls['lastname'].valid, 'errmsg' : !form.controls['lastname'].pristine }">
<input type="text" [formControl]="form.controls['lastname']">
</div>
<div class="col-sm-8">
<button type="submit">Register now</button>
</div>
</form>
Form validation classes work on the below cases
ng-valid - Boolean Tells whether an item is currently valid based on the rules you placed.
ng-invalid - Boolean Tells whether an item is currently invalid based on the rules you placed.
ng-pristine - Boolean True if the form/input has not been used yet.
ng-dirty - Boolean True if the form/input has been used.
ng-touched - Boolean True if the input has been blurred.
For more info refer here
https://scotch.io/tutorials/angularjs-form-validation
Upvotes: 1