Angular

Last Updated: 8/30/2023

Add Validation

  • We assign 1 or more validators when creating formcontrol object
  • FormControl:
    • param 1 - formstate - initial value set to the form control - set to empty string
    • param 2 - validatorfn or array of validatorfn - pass function reference
  • Import Validators from forms
  • Validators has static methods for various kind of validation. eg required, minlength, maxlength, pattern etc
username:  new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
  • In template add validation error messages
  • Use get method to access any form control object in the form group
<div *ngIf="form.get('username').touched && form.get('username').invalid">
	<div>Username is required</div>
</div>

Simplied

  • Define a property to access the object
get username() {
  return this.form.get('username');
}
<div *ngIf="username.touched && username.invalid">
	<div>Username is required</div>
</div>