Issue
I have created a login page with form
tag, I want client side validation when user click Submit button, but nothing happens, Checkform
method is not getting fired.
This is my code
<div>
<form class="login">
<p class="title">Log in</p>
<input type="text" class="form-control id="username" id="txtUsername" required>
<div class="invalid-feedback">
Please provide Username
</div>
<input class="form-control type="text" id="email" id="txtPass" required>
<div class="invalid-feedback">
Please provide Password
</div>
<br>
<button type="button" onclick="Checkform()">
<span class="state">Log in</span>
</button>
</form>
</div>
I have added bootstrap
classes for validation and also a method in .ts
file which should fire when I click on submit button
<div class="invalid-feedback">
Please provide Username
</div>
<div class="invalid-feedback">
Please provide Password
</div>
Checkform(){
var form = document.getElementsByClassName('login')[0] as HTMLFormElement;
if (form.checkValidity() === false) {
}
form.classList.add('was-validated');
}
How can I make client side validation for empty fields and fire a method when user click on Submit button ?
Solution
Clint side validation I have fixed using Reactive forms
. Its easy to develop 😀
First add ReactiveFormsModule
in imports
section in the app.modules.ts
file. In your component.ts
file write below code
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class HomeComponent implements OnInit {
loginForm :FormGroup;
submitted=false;
constructor(private formBuilder: FormBuilder) {
this.initializeForm();
}
initializeForm()
{
this.loginForm = this.formBuilder.group({
userName: ['', Validators.required],
email: ['',Validators.email]
});
}
UserLogin()
{
this.submitted = true;
if(this.loginForm.invalid)
{
return
}
}
}
This is how you can design component.html
file
<form [formGroup]="loginForm" (ngSubmit)="UserLogin()">
<div class="form-group">
<input type="text" class="form-control" [ngClass]="{'is-invalid' :submitted && loginForm.controls['userName'].errors}"
formControlName="userName" placeholder="Username">
</div>
<div class="form-group">
<input type="text" class="form-control mt-2" [ngClass]="{'is-invalid' :submitted && loginForm.controls['email'].errors}"
formControlName="email" placeholder="Email">
</div>
<button class="btn btn-primary" type="submit">
<span class="state">Log in</span>
</button>
</form>
Inside initializeForm()
we have userName
and email
, these names should be the formControlName
in .html
file. You can add as many as fields you need. This is how login page looks like
If you want detailed information visit this.
Answered By - R15
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.