Sunday, October 24, 2021

Basic Angular Reactive Form Validation with Validation messages

 1. app.component.html 



<form [formGroup] = "frmabc" (ngSubmit) = "submit()" >
  <input type="text" formControlName="firstName" maxlength="10"/>
  <div *ngIf="frmabc.controls.firstName.invalid &&
  (frmabc.controls.firstName.dirty || frmabc.controls.firstName.touched)"
  class="alert">
 
  <div *ngIf="frmabc.controls.firstName.errors?.required">
    First Name is required.
  </div>
  <div *ngIf="frmabc.controls.firstName.errors?.minlength">
    First Name must be at least 4 characters long.
  </div>
 
 
</div>
<input type="text" formControlName="lastName"/>
<div *ngIf="frmabc.controls.lastName.invalid &&
(frmabc.controls.lastName.dirty || frmabc.controls.lastName.touched)"
class="alert">

<div *ngIf="frmabc.controls.lastName.errors?.required">
  Last Name is required.
</div>
<div *ngIf="frmabc.controls.lastName.errors?.minlength">
  Last Name must be at least 4 characters long.
</div>

</div>

<button type="submit" [disabled]= "!frmabc.valid">dfdsf</button>
</form>


2. app.component.ts 


import { Component} from '@angular/core';
import { FormsModule , FormBuilder , FormControl, Validators , FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  title = 'angform1';
  // Patterns
  //readonly PAT_NAME = "^[a-zA-Z ]{2,20}$";
  //readonly PAT_EMAIL = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[.][a-zA-Z]{2,4}$";
 
  frmabc = this.fb.group({
    firstName : ['', [Validators.required , Validators.minLength(4) , Validators.maxLength(10)]],
    lastName : ['' , [Validators.required , Validators.minLength(4) , Validators.maxLength(10)]]
  });
 
  constructor(private fb : FormBuilder) {}
  submit()
  {
    alert ( this.frmabc.get('firstName')?.value + " " + this.frmabc.get('lastName')?.value );
  }
 
}


NOTES : 

1. maxLength validator put in ts file will not by itself restrict the input to max length. To restrict the input to maxlength, use the maxlength attribute in .html also, in addition to the one in .ts. 

<input .... maxlength = "10" /> 

2.  If you get "possible null value" error, do not forget to use the "?" operator. 



No comments:

Post a Comment

MCP v2 changes things a lot for the developer

 As I go deep into MCP v2, overwhelming changes are being noticed: Session is being done away with. Logging is removed - all you can do is u...