Blog>
Snippets

Securing Angular forms with built-in validators

Create a form with Angular reactive forms and apply built-in validators to prevent SQL injection and other attacks.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
Import necessary classes from @angular/forms to create a reactive form with validators.
constructor(private formBuilder: FormBuilder) { this.createForm(); }
Inject the FormBuilder service in the constructor and call the 'createForm' method to initialize the form.
createForm(): void {
  this.myForm = this.formBuilder.group({
    username: ['', [Validators.required, Validators.minLength(4)]],
    password: ['', [Validators.required, Validators.minLength(8)]]
  });
}
Create a form with reactive form controls 'username' and 'password'. Apply built-in validators like 'required', 'minLength' to ensure basic validation against improper input.
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input formControlName="username" type="text" placeholder="Username">
  <input formControlName="password" type="password" placeholder="Password">
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
This is the Angular template that uses the form group 'myForm'. The form inputs have formControlName attributes that link them to the form controls. The submit button is disabled if the form is invalid.
onSubmit(): void {
  if (this.myForm.valid) {
    const formData = this.myForm.value;
    // Process form data
    console.log('Form data is valid:', formData);
  } else {
    console.log('Form is not valid.');
  }
}
Create an 'onSubmit' method to handle the form submission. It checks if the form is valid before processing the data.