Reputation: 21
I am working to develop a secure form using angular 5 and Bootstrap 4. How can I validate form runtime before form submission? Please guide or share any article regarding reactive validation in angular 5. Where I can learn validation about the text, number, email, description etc.
This is my first question at StackOverflow. Thank you.
Upvotes: 2
Views: 3897
Reputation: 47
For reactive forms, instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.
Here's an example of form validation in reactive forms using built-in validators.
Typescript file:
ngOnInit(): void {
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4)
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
}
Template file:
<input id="name" class="form-control"
formControlName="name" required >
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
Upvotes: 2